Swift 异步加载图像 [英] Swift async load image
本文介绍了Swift 异步加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理来自 url 异步的显示图像.我试图为下载图像创建一个新线程,然后在 main thread
上刷新.
I am working on show image from url async. I have tried to create a new thread for download image and then refresh on main thread
.
func asyncLoadImg(product:Product,imageView:UIImageView){
let downloadQueue = dispatch_queue_create("com.myApp.processdownload", nil)
dispatch_async(downloadQueue){
let data = NSData(contentsOfURL: NSURL(string: product.productImage)!)
var image:UIImage?
if data != nil{
image = UIImage(data: data!)
}
dispatch_async(dispatch_get_main_queue()){
imageView.image = image
}
}
}
当我试图调试它时,当涉及到 dispatch_async(downloadQueue) 时,它跳出了 func.有什么建议吗?谢谢
When I was trying to debug that, when it comes to dispatch_async(downloadQueue), it jumps out the func. Any suggestion? Thx
推荐答案
**Swift 5.0+ 更新代码:
**Swift 5.0+ updated Code :
extension UIImageView {
func imageFromServerURL(_ URLString: String, placeHolder: UIImage?) {
self.image = nil
//If imageurl's imagename has space then this line going to work for this
let imageServerUrl = URLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
if let url = URL(string: imageServerUrl) {
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
//print("RESPONSE FROM API: (response)")
if error != nil {
print("ERROR LOADING IMAGES FROM URL: (error)")
DispatchQueue.main.async {
self.image = placeHolder
}
return
}
DispatchQueue.main.async {
if let data = data {
if let downloadedImage = UIImage(data: data) {
self.image = downloadedImage
}
}
}
}).resume()
}
}
}
现在只要你需要这样做就可以从服务器 url 加载图像:
Now wherever you required just do this to load image from server url :
- 使用 swift 5.0 + 使用占位符图像的更新代码:UIImageView.imageFromServerURL(URLString:here server url",placeHolder: uiimage 格式的占位符图片)
简单!
这篇关于Swift 异步加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文