Building a Swift Async/Await Image Downloader: A Practical Example
In this article, we will create a Swift Async/Await image downloader, leveraging the powerful concurrency features of Swift. This practical example will guide you through the process, starting from a basic URLSession data task to advanced error handling and caching techniques.
Example 1: Basic Image Downloader Using URLSession
Defining the Image URL
let imageUrl = URL(string: "https://via.placeholder.com/150")!Downloading Image Data with URLSession
func downloadImageData(from url: URL) async throws -> Data {
let request = URLRequest(url: url)
let (data, _) = try await URLSession.shared.data(for: request)
return data
}Displaying the Downloaded Image
Task {
do {
let data = try await downloadImageData(from: imageUrl)
let image = UIImage(data: data)
// Display the image
} catch {
print("Error: \(error.localizedDescription)")
}
}Example 2: Creating an Image Cache
Image Cache Class
class ImageCache {
private var cache: [URL: UIImage] = [:]
func cacheImage(_ image: UIImage, for url: URL) {
cache[url] = image
}
func image(for url: URL) -> UIImage? {
return cache[url]
}
}Example 3: Advanced Image Downloader with Error Handling and Caching
Image Downloader Class
class ImageDownloader {
private let imageCache = ImageCache()
func downloadImage(from url: URL) async throws -> UIImage {
if let cachedImage = imageCache.image(for: url) {
return cachedImage
}
let data = try await downloadImageData(from: url)
guard let image = UIImage(data: data) else {
throw NSError(domain: "InvalidImageData", code: 0, userInfo: nil)
}
imageCache.cacheImage(image, for: url)
return image
}
}Using the Advanced Image Downloader
let imageDownloader = ImageDownloader()
Task {
do {
let image = try await imageDownloader.downloadImage(from: imageUrl)
// Display the image
} catch {
print("Error: \(error.localizedDescription)")
}
}Conclusion
By utilizing Swift’s Async/Await features and URLSession, we’ve created a powerful image downloader with caching capabilities. This practical example demonstrates how to build efficient and effective networking code for your Swift applications.
If you enjoyed the article and would like to show your support, be sure to:
👏 Applaud for the story (50 claps) to help this article get featured
👉 Follow me on Medium
Check out more content on my Medium profile





