There are a few finicky details that need to be paid attention to when lazily loading images in the background, like:
- not starting too many parallel downloads
- handling the concurrency
- cancelling downloads when images are not needed anymore
I recommend to use one of the two popular libraries that do the trick in just a few lines of code: SDWebImage and Kingfisher. Both are easy to get via Cocoapods and are quite similar in API and supported features.
After adding the SDWebImage pod to the project:
Given an image view and a URL to load the image from, loading the image with an activity indicator is as simple as:
imageView.sd_setShowActivityIndicatorView(true) imageView.sd_setIndicatorStyle(.gray) imageView.sd_setImage(with: imageURL)
Pretty much the same for Kingfisher:
Loading an image from an URL with activity indicator and displaying it in the image view:
imageView.kf.indicatorType = .activity imageView.kf.setImage(with: imageURL)
There is a nice cheat sheet that demonstrates common cases like customizing the indicator or getting notified when downloads complete.
- SDWebImage supports progressive display of the image while loading is in progress via options: [.progressiveDownload] which is nice when loading larger images. This is not supported in Kingfisher as of now.
- SDWebImage has support for Webp images included as a subspec that works out of the box, while for Kingfisher it’s an external plugin KingfisherWebP that requires extra configuration - for applications that have a lot of resources, webp helps delivering higher quality with shorter download times.
- SDWebImage is implemented in Objective-C, Kingfisher in Swift 4.
Here is an example project that includes a UITableViewController example for both libraries which are included via Cocoapods: