Loading images asynchronously
There are a few details that need to be paid attention to when loading images from URLs in your Swift code:
- loading and decoding the image on a background thread
- updating the UIImageView on the main thread
- not starting too many parallel downloads
- 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 or 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:
import UIKit
import SDWebImage
class ExampleViewController: UIViewController {
@IBOutlet weak var imageView : UIImageView!
// ...
func loadImage() {
let imageURL = URL(string: "https://upload.wikimedia.org/wikipedia/commons/1/15/Red_Apple.jpg")!
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:
import UIKit
import Kingfisher
class ExampleViewController: UIViewController {
@IBOutlet weak var imageView : UIImageView!
// ...
func loadImage() {
let imageURL = URL(string: "https://upload.wikimedia.org/wikipedia/commons/1/15/Red_Apple.jpg")!
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
-
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 images with shorter download times.
-
SDWebImage is implemented in Objective-C, Kingfisher in Swift.