iOS Concurrency with GCD & Operations

Sep 12 2023 · Swift 5.8, macOS 13, iOS 16, Xcode 14.3

Part 1: Grand Central Dispatch

06. The Right Way to Download Images

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 05. Challenge: A Better Way to Download Images Next episode: 07. Use a Group of Tasks

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 06. The Right Way to Download Images

The Right Way to Download Images

There’s an even easier way to download images off the main queue.

URLSession methods run off the main queue by default, so you don’t need to dispatch them to a background queue. If you’ve done the URLSession course, you used the Swift concurrency method data(from:) and simply awaited data and response. Here, you’ll use the older method to download data — dataTask(with:) — and you’ll write a completion handler to update the images array on the main queue.

Down at the bottom of ImageStore, in the method downloadImageWithUrlSession(index: Int), create a data task with a trailing closure for its completion handler:

func downloadImageWithUrlSession(index: Int) {
  URLSession.shared.dataTask(with: images[index].url) {
    [weak self] data, _, _ in

  }.resume()
}
  • You’re using the shared URLSession configuration and the url for this image.
  • The data task returns 3 values: data, response and error. You won’t use response or error, so just type underscores to ignore the parameters.
  • The data task is created in suspended mode, so you must tell it to resume.

You still have to capture self, then store the data as a UIImage:

guard let self else { return }
if let data, let decodedImage = UIImage(data: data) {

}

You checked for data and created a UIImage from it. Now you’re in exactly the same situation as the other helper method, so dispatch to main in the same way:

DispatchQueue.main.async {
  self.images[index].image = decodedImage
}

Finally, back in ContentView, switch to using your new method:

//store.downloadImageOffMainQueue(index: image.id)
store.downloadImageWithUrlSession(index: image.id)

Build and run to see that scrolling is still responsive. The main difference is for you, the developer: URLSession dataTask is asynchronous, so you don’t have to dispatch it to a background queue. There are still problems: The images appear and disappear, load slowly and continue reloading when you scroll away. To make the experience perfect, you’ll need a way to start and cancel these requests and cache their results. These are much easier to do with operations, which you’ll learn about in Part 3 of this course.