Episode #386

Working with Remote Images

Series: Making a Podcast App From Scratch

16 minutes
Published on April 11, 2019

This video is only available to subscribers. Get access to this video and 584 others.

Working with images from the network is such a common task in iOS development. In this episode we'll cover a useful library called Kingfisher, which gives you a simple API for downloading and caching images from the network. We also look at two ways for configuring our image view, one using User-Defined Runtime Attributes and the other by using awakeFromNib in code.

Episode Links

Configuring the Image View

Let's start by customizing the presentation of our image view. This will also serve as the default presentation if no image is available (or if image download fails).

override func awakeFromNib() {
    super.awakeFromNib()

    artworkImageView.backgroundColor = Theme.Colors.gray3
    artworkImageView.layer.cornerRadius = 10
    artworkImageView.layer.masksToBounds = true

    // ...
}

Adding Kingfisher

We'll use CocoaPods to install a useful library for dealing with remote images:

$ pod init

Then, in the generated Podfile:

platform :ios, '12.0'

target 'PodcastApp' do
  use_frameworks!


  pod 'Kingfisher', '~> 5.3.1'
end

Then we can run pod install to install it and open the new workspace it created for us.

Using Kingfisher to Download Podcast Artwork

In the SearchResultCell class:

func configure(with result: SearchResult) {
    if let url = result.artworkUrl {
        let options: KingfisherOptions = [
            .transition(.fade(0.5))
        ]
        artworkImageView.kf.setImage(with: url, options: options) 
   }

   // ...
}

Handling Reusable Cells

If image reuqests are in flight when we try to reuse the cell, we need to cancel the request, otherwise we risk having the wrong image being displayed on a cell.

The right place to put this code is in prepareForReuse:

override func prepareForReuse() {
    super.prepareForReuse()

    // ...

    artworkImageView.kf.cancelDownloadTask()
    artworkImageView.image = nil
}

This episode uses Xcode 10.2, Swift 5.0.