top of page
  • Writer's pictureJennifer Eve Vega

Downloading Images without using a Library

Updated: Jul 25, 2023

If you are working on a screen that requires loading a lot of images (I'm talking about hundreds or thousands of images) from a URL source, you have to make sure that your app won't lag while scrolling down the images.


To do that, we have to download those images on different thread (make sure it's not the main thread so that it won't block any user interactions in the app). One way to do it is to use different Image Downloader libraries.


But, you can also do it without using any library!


And that is by using URLSession. With this, you don't have to worry about concurrency and UI issues as it will be downloading the images concurrently in different thread.


Here's how you can do it:

private func downloadImageWithURLSession(_ imageURLStr: String,
cell: ImageCollectionViewCellProtocol) {
        
   guard let url = URL(string: imageURLStr) else {
       return
   }
        
   let urlRequest = URLRequest(url: url)
   URLSession.shared.dataTask(with: urlRequest) { data, urlResponse, _ in
       guard let data = data,
             let image = UIImage(data: data),
             let urlStr = urlRequest.url?.absoluteString,
             urlStr == imageURLStr else { //add image validation
           return
       }
            
       DispatchQueue.main.async {
           cell.showImage(image)
       }
   }
   .resume()
   
}

Post Update:

I received a comment from Dave Poirier that I should also check if the image that's being downloaded is the correct image that should be shown in this cell. The reason is that cells are being reused when they are not visible, which means, if we don't add image validation, there's a possibility that the cell may show incorrect image as you scroll. See more about his comment here:

Thank you Dave for your comment. I learned something today.


Recent Posts

See All
bottom of page