Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift async load image

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

like image 451
Janice Zhan Avatar asked May 04 '16 05:05

Janice Zhan


Video Answer


1 Answers

**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 :

  1. Using swift 5.0 + updated code using placeholder image : UIImageView.imageFromServerURL(URLString:"here server url",placeHolder: placeholder image in uiimage format)

Simple !

like image 61
Shobhakar Tiwari Avatar answered Sep 25 '22 15:09

Shobhakar Tiwari