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 } } }
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+ 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() } } }
Now wherever you required just do this to load image from server url :
Simple !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With