Asynchronous image downloads

There are a few finicky details that need to be paid attention to when lazily loading images in the background, like:

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.

SDWebImage

After adding the SDWebImage pod to the project:

pod 'SDWebImage'

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)

Kingfisher

Pretty much the same for Kingfisher:

pod '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.

Differences between the libraries: SDWebImage vs. Kingfisher

Example project

Here is an example project that includes a UITableViewController example for both libraries which are included via Cocoapods:

Image download in iOS via Kingfisher

Btn training bbbdf557d2 Next iOS training: 10. - 14. September 2018, München
Btn read 3c0e607615 Read on: iOS developer blog
Btn subscribe 930758687e Subscribe: Email · Twitter
Btn share 3139847d21 Share: Email · Twitter
Btn support 789320554c Support the iOS developer blog - Become a patron
Btn about 5378472193 About me
Btn email 4d2439fc5b Email to Ralf Ebert «info@ralfebert.de»