Updated 14 December 2016
Suppose you want to display the number of images and you have to download that images from the Url. As downloading the images, view get stuck and can’t display all images, it will take too much time. To Resolve that problem, download images from URLSession and put a place holder until your images get displayed. Here is the Code :-
1 2 |
imageViewObject.image = UIImage(named: "placeholder") self.downloadImage(url: NSURL(string: dict["image_path"]!) as! URL , tag: bannerTag) |
image_path = image URL
bannerTag = tag of image
here is Downloading Image Function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) { URLSession.shared.dataTask(with: url) { (data, response, error) in completion(data, response, error) }.resume() } func downloadImage(url: URL , tag : Int) { // print("Download Started") getDataFromUrl(url: url) { (data, response, error) in guard let data = data, error == nil else { return } // print(response?.suggestedFilename ?? url.lastPathComponent) // print("Download Finished") DispatchQueue.main.async() { () -> Void in if let temp : UIImageView = self.view.viewWithTag(tag) as? UIImageView{ temp.image = UIImage(data: data) } else{ // print("ff") } } } } |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.