Leave a rating/review
Notes: 13. Challenge: Download Images
URLSessionConfiguration - Apple Developer URLSession - Apple Developer
Hello and welcome! Time for a little challenge for you. By now you should have a good idea about how to download a file using URLSession.
Your challenge is to take the current app and have it download some album art. I’ve added a method to SongDownloader called downloadArtwork. I want you to use the artwork property of MusicItem in order to create the URL from where to download the album artwork image.
Remember, when you download an image it’ll be downloaded as a data object. You’ll need to convert that to an image, and then assign that image to the artworkImage property of SongDetailView.
Make sure you remember the golden rule about having all UI updates happen on the main thread. Pause the video, give this a try, and I’ll see you in a bit!
Welcome back. How did it go? Let’s go over how you could’ve solved the challenge. Open SongDownloader.swift and add this code where the TODO was:
let (downloadURL, response) = try await session.download(from: url)
Same pattern whereyou use URLSession to download a file from the network. Next, check the response’s status code to ensure the request was successful:
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200
else {
throw ArtworkDownloadError.invalidResponse
}
If the status code is not 200, you throw an invalidResponse error. Finally, add this code at the end of the method:
do {
return try Data(contentsOf: downloadURL)
} catch {
throw ArtworkDownloadError.failedToDownloadArtwork
}
Because the downloaded file is an image, you use the contentsOf static method on Data in order to create a Data object from the file and return its contents.
The call can throw errors, so you wrap all of this inside a do-catch block and throw an error should something go wrong.
Switch over to SongDetailView.swift and add this code where the TODO was:
do {
let data = try await downloader.downloadArtwork(at: artworkURL)
} catch {
print(error)
}
This code, wrapped inside a do-catch block, calls the downloadArtwork method and stores its returned data. At the end of the do block, add this code:
guard let image = UIImage(data: data) else {
return
}
This tries to create a UIImage from the Data that should contain the downloaded album artwork. Finally, update the artworkImage property:
artworkImage = image
Time to build and run your code.
As soon as you launch the app your code to dowload the artwork should run. Depending on the speed of your connection you should see the downloaded album artwork replace the default image.
Of note, the error that can get thrown and is caught in the catch statement is currently just being handled via a print statement. Once you’re doing doing any tests be sure to remove it:
catch {
}
Fantastic work! Another successful challenge for you. In the next episode we’ll take a look at how to show the progress of your download. See ya there! :)