Leave a rating/review
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
sharedURLSession configuration and theurlfor this image. -
The data task returns 3 values:
data,responseanderror. 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.