2016-03-07 64 views
3

我想從使用Alomofire和swiftyJSON的json加載圖像。 JSON是字典:從alamofire swift在tableview單元格中加載圖像

{"name": {"image": "https://...",}} 

Alamorefire和SwiftyJSON

var imageLoad: String! 

Alamofire.request(.GET, url).responseJSON { (response) -> Void in 
    if let value = response.result.value { 
    let json = JSON(value) 

    if let jsonDict = json.dictionary { 

     let image = jsonDict["name"]!["image"].stringValue 
     print(image) // https://.... 
     self.imageLoad = image   
    } 
    self.tableView.reloadData() 
    } 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TVCell 

// Configure the cell... 

cell.imageTableView.image = UIImage(named: imageLoad) // not working "fatal error: unexpectedly found nil while unwrapping an Optional value" 

如果有人可以幫助?如果有另一種方式隨意寫。

回答

0

如果您已經使用Alamofire,您可以嘗試AlamofireImage這是一個圖像組件庫Alamofire

然後,取圖像就像下面這樣:

import AlamofireImage 

Alamofire.request(.GET, "https://httpbin.org/image/png") 
     .responseImage { response in 

      if let image = response.result.value { 
       print("image downloaded: \(image)") 
      } 
     } 
0

正如Bear with me說,你可以使用AlamofireImage,

https://github.com/Alamofire/AlamofireImage

我做了這個對於斯威夫特3,希望它可以幫助:

在執行該表的控制器中查看數據源

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Cell 
    NetworkService.shared.requestImage(path: path, completionHandler: {image in 
      cell.photo?.image = image 
     }) 
    } 
    return cell 
} 

在我的網絡服務(我用的共享來實現單,它像的getInstance)我實現了requestImage函數調用AlamofireImage:

func requestImage(path: String, completionHandler: @escaping (Image) -> Void){ 
    Alamofire.request("\(path)").responseImage(imageScale: 1.5, inflateResponseImage: false, completionHandler: {response in 
     guard let image = response.result.value else{ 
      print(response.result) 
      return 
     } 
     DispatchQueue.main.async { 
      completionHandler(image) 
     } 
    }) 
} 

正如你可以看到我使用GCD主隊列管理completionHandler只是爲了確保它是處理視圖修改的主要隊列。

+1

wouldnt這有可能創造一個比賽c ondition?如果單元格正在加載圖像,則會被回收,並且第二次immage的加載速度會比第一次更快。 – Jeremie

2

如果您使用的是Alamofire,請嘗試AlamofireImage。但直接在uiimageview上使用af_快捷方式。自動獲得緩存,佔位符圖像,並且如果您使用可以回收單元格的表視圖,則可以取消未完成的請求。

通過指定佔位符圖像,圖像視圖使用佔位符圖像,直到下載遠程圖像。

let imageView = UIImageView(frame: frame) 
let url = URL(string: "https://httpbin.org/image/png")! 
let placeholderImage = UIImage(named: "placeholder")! 

imageView.af_setImage(withURL: url, placeholderImage: placeholderImage) 
從URL從alamofire swift3的tableview細胞

https://github.com/Alamofire/AlamofireImage

+0

我上面提到的與您的做法相同。但我正在使用可重複使用的單元格。圖像也反覆加載到單元格上。你能幫我嗎 ? – Charmi

+0

可重複使用的單元格很棘手,因爲您可能會在競爭條件下結束(如果您啓動了下載並將該單元格與其他圖像重新使用等)。解決方法是下載圖像並在獲取URL時緩存它。您可以使用DispatchGroup()來延遲獲取URLS的URL調用的完成回調,直到下載圖像。當然,如果圖像真的很大,這可能不適用於所有場景。在這一點上,你應該嘗試一些延遲加載的圖像,但你也必須跟蹤隊列中的下載,以避免競爭條件... – Jeremie

1

負荷的形象: -

//你需要安裝莢 'AlamofireImage',「〜> 3。0' 莢

import Alamofire 
    import AlamofireImage 

// put into cellForRowAt 

    Alamofire.request(self.profileImgArr[indexPath.row]).responseData { (response) in 
        if response.error == nil { 
          print(response.result) 

          // Show the downloaded image: 
          if let data = response.data { 
            cell.profileImg.image = UIImage(data: data) 
           }     
         } 
       } 
1

我共享代碼實現使用斯威夫特3AlamofireImage

import UIKit 
import AlamofireImage 

class MovieViewCell: UICollectionViewCell { 

@IBOutlet weak var titleLabel: UILabel! 
@IBOutlet weak var overviewLabel: UILabel! 
@IBOutlet weak var posterView: UIImageView! 

func configure(for movie: Movie) { 
    titleLabel.text = movie.title 
    overviewLabel.text = movie.overview 

    let url = URL(string: movie.poster_path!)! 
    posterView.af_setImage(withURL: url) 
} 

override func prepareForReuse() { 
    super.prepareForReuse() 

    posterView.af_cancelImageRequest() 
    posterView.image = nil 
} 
} 

此外,您將需要的CocoaPods

platform :ios, '10.0' 

inhibit_all_warnings! 
use_frameworks! 

target 'MovieApp' do 
    pod 'Alamofire', '~> 4.5' 
    pod 'AlamofireImage', '~> 3.3' 
end 

正式文件AlamofireImagean ImageCell.swift example

1

我推薦使用不同的庫來加載圖像。我們總是在我們的項目中這樣做。

有一個簡單而智能的庫,可以處理從緩存到佔位符圖像的所有內容。

它的名字是翠鳥 https://github.com/onevcat/Kingfisher

您可以直接在ImageView的與URL中使用它JSON 例子:

let url = URL(string: "url_of_your_image") 
imageView.kf.setImage(with: url) 

這是最基本的異步圖像加載方法,

看看你自己:)

+1

我建議將上面的兩行樣本集成到代碼示例中提供的代碼示例題。這將使答案更有幫助。 – jkwuc89

相關問題