Leave a rating/review
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.
-
In ContentView, call
downloadImageOffMainQueue(index:)instead ofdownloadImageOnMainQueue(index:). -
In ImageStore, copy-paste and adapt the code in
downloadImageOnMainQueue(index:)to implementdownloadImageOffMainQueue(index:). This method should download each image on a utility dispatch queue and update theimagesarray. 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.