[英]load image from url in tableview cell from alamofire swift
I am trying to load image from json using Alomofire and swiftyJSON. 我正在尝试使用Alomofire和swiftyJSON从json加载图像。 Json is dictionary:
Json是字典:
{"name": {"image": "https://...",}}
Alamorefire and SwiftyJSON 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"
If anyone can help? 如果有人可以帮忙吗? If there is another way feel free to write.
如果有另一种方式随意写。
If you are using Alamofire
, try AlamofireImage
. 如果您使用的是
Alamofire
,请尝试AlamofireImage
。 But use the af_
shortcuts directly on uiimageview. 但是直接在uiimageview上使用
af_
快捷方式。 Automatically you will get caching, placeholder images, and you can cancel outstanding requests if you are using a table view which could recycle the cells. 自动您将获得缓存,占位符图像,并且如果您使用可以回收单元格的表视图,则可以取消未完成的请求。
By specifying a placeholder image, the image view uses the placeholder image until the remote image is downloaded. 通过指定占位符图像,图像视图使用占位符图像,直到下载远程图像。
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)
https://github.com/Alamofire/AlamofireImage https://github.com/Alamofire/AlamofireImage
I share a code implemented using Swift 3 and AlamofireImage : 我分享了使用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
}
}
Also, you will need Cocoapods : 此外,您将需要Cocoapods :
platform :ios, '10.0'
inhibit_all_warnings!
use_frameworks!
target 'MovieApp' do
pod 'Alamofire', '~> 4.5'
pod 'AlamofireImage', '~> 3.3'
end
Official documentation AlamofireImage and an ImageCell.swift example 官方文档AlamofireImage和ImageCell.swift示例
load image from url in tableview cell from alamofire swift3 : - 从alamofire swift3的tableview单元格中的url加载图像: -
//you need install pod 'AlamofireImage', '~> 3.0' pod //你需要安装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)
}
}
}
I recommend using a different library for loading the images. 我建议使用不同的库来加载图像。 We always do this in our projects.
我们总是在我们的项目中这样做。
There is an easy and smart library which handles pretty much everything from caching to placeholder image. 有一个简单而智能的库,可以处理从缓存到占位符图像的所有内容。
It's name is Kingfisher https://github.com/onevcat/Kingfisher 它的名字是Kingfisher https://github.com/onevcat/Kingfisher
You can use it directly on the ImageView with the URL from JSON Example: 您可以使用JSON中的URL直接在ImageView上使用它:
let url = URL(string: "url_of_your_image")
imageView.kf.setImage(with: url)
This is the most basic Asynchronous image loading method, 这是最基本的异步图像加载方法,
Take a look for yourself :) 看看你自己:)
If you're already using Alamofire
, you can try AlamofireImage
which is an image component library for Alamofire
. 如果您已经使用
Alamofire
,你可以尝试AlamofireImage
这是一个图像组件库Alamofire
。
Then, fetching image is done like this: 然后,像这样完成提取图像:
import AlamofireImage
Alamofire.request(.GET, "https://httpbin.org/image/png")
.responseImage { response in
if let image = response.result.value {
print("image downloaded: \(image)")
}
}
As Bear with me said you can use AlamofireImage, 跟熊一起说你可以用AlamofireImage,
https://github.com/Alamofire/AlamofireImage https://github.com/Alamofire/AlamofireImage
I made this for Swift 3, hope it can help: 我为Swift 3做了这个,希望它可以帮助:
In the controller implementing the tableViewDataSource 在控制器中实现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
}
In my NetworkService (I use the shared to implement singleton, it's like getInstance) I implemented the requestImage function calling AlamofireImage: 在我的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)
}
})
}
As you can see I use the GCD for main queue to manage the completionHandler just to be sure that it is the main queue which handles the view modification. 正如您所看到的,我使用GCD作为主队列来管理completionHandler,以确保它是处理视图修改的主队列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.