iOS Concurrency with GCD & Operations

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

Part 1: Grand Central Dispatch

05. Challenge: A Better 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: 04. Use Dispatch Work Items Next episode: 06. The Right Way to Download Images

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: 05. Challenge: A Better Way to Download Images

Challenge: A Better Way to Download Images

In the first episode, I showed you the sample app for this course. It’s unresponsive to user interaction because the image downloads all happen on the main thread, which should only be used for user interface tasks.

  1. In ContentView, call downloadImageOffMainQueue(index:) instead of downloadImageOnMainQueue(index:).
  2. In ImageStore, copy-paste and adapt the code in downloadImageOnMainQueue(index:) to implement downloadImageOffMainQueue(index:). This method should download each image on a utility dispatch queue and update the images array. Remember to perform any user interface-related code on the main queue. You’ll need this code fragment:
[weak self] in
  guard let self else { return }

Pause this video while you make these changes, then resume playing the video to see my solution.

You’re about to implement the new method. Before you forget, call it in ContentView.

store.downloadImageOffMainQueue(index: image.id)  // change On to Off

Next, in ImageStore, set up your utility dispatch queue in downloadImageOffMainQueue(index:)

DispatchQueue.global(qos: .utility).async { 
}

Add the code to capture self:

DispatchQueue.global(qos: .utility).async { [weak self] in
  guard let self else { return }
}

This is the only ImageStore in the app, so a weak capture is OK: The ImageStore exists whenever the app is active, so the closure will be called when the network request finishes.

Next, copy the if closure from downloadImageOnMainQueue(index:) into your new async closure:

if let data = try? Data(contentsOf: self.images[index].url),
  let decodedImage = UIImage(data: data) {
  images[index].image = decodedImage
}

Now remember, ImageStore publishes images to a SwiftUI view, which is user interface, so you must dispatch this images-modifying code back to the main queue:

[//] $ Don’t use Embed, just move images line up after creating closure

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

Build and run to see that the user interface is now much more responsive: Scrolling is much smoother.