[英]How to load an image from URL and display it in tableView cell (Swift 3)
[英]load image from url in tableview cell from alamofire swift
我正在嘗試使用Alomofire和swiftyJSON從json加載圖像。 Json是字典:
{"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"
如果有人可以幫忙嗎? 如果有另一種方式隨意寫。
如果您使用的是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)
我分享了使用Swift 3和AlamofireImage實現的代碼:
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
從alamofire swift3的tableview單元格中的url加載圖像: -
//你需要安裝pod'AlamofireImage','〜> 3.0'pod
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)
}
}
}
我建議使用不同的庫來加載圖像。 我們總是在我們的項目中這樣做。
有一個簡單而智能的庫,可以處理從緩存到占位符圖像的所有內容。
它的名字是Kingfisher https://github.com/onevcat/Kingfisher
您可以使用JSON中的URL直接在ImageView上使用它:
let url = URL(string: "url_of_your_image")
imageView.kf.setImage(with: url)
這是最基本的異步圖像加載方法,
看看你自己:)
如果您已經使用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)")
}
}
跟熊一起說你可以用AlamofireImage,
https://github.com/Alamofire/AlamofireImage
我為Swift 3做了這個,希望它可以幫助:
在控制器中實現tableViewDataSource
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
}
在我的NetworkService中(我使用共享實現單例,它就像getInstance)我實現了調用AlamofireImage的requestImage函數:
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,以確保它是處理視圖修改的主隊列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.