-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
239: Practice Exercise: Building a Concurrent Image Downloader with Caching
We've spent a lot of time talking about the theory of async/await and Actors, but the real magic happens when you combine them to solve a common problem: loading a bunch of assets without freezing the UI or crashing your app due to a data race. I want to show you how to build a concurrent image downloader that handles caching so we don't waste the user's data fetching the same image twice.
Storing Images without the Chaos
First, we need a place to keep the images we've already downloaded. I'm going to start by creating a cache. Since we'll be accessing this cache from multiple concurrent tasks, we can't just use a standard dictionary in a class—that's a one-way ticket to a Thread Sanitizer warning or a hard crash.
actor ImageCache {
private var cache: [URL: UIImage] = [:]
func image(for url: URL) -> UIImage? {
return cache[url]
}
func insert(_ image: UIImage, for url: URL) {
cache[url] = image
}
}
I used an actor here because it guarantees that only one task can access the cache dictionary at a time. It handles the synchronization for us, so we don't have to mess around with manual locks or dispatch queues.
The Actual Download Logic
Now we need the logic to actually grab the data. I'll wrap this in a service class. I'm keeping this simple: it'll check the cache first; if the image is missing, it'll hit the network, store the result, and return it.
class ImageDownloader {
let cache = ImageCache()
func fetchImage(from url: URL) async throws -> UIImage {
// Check if we already have it
if let cached = await cache.image(for: url) {
return cached
}
// Otherwise, go get it
let (data, _) = try await URLSession.shared.data(from: url)
guard let image = UIImage(data: data) else {
throw URLError(.cannotDecodeContentData)
}
// Save it for next time
await cache.insert(image, for: url)
return image
}
}
Fetching Everything at Once
This is where it gets interesting. If we have a list of twenty images, we don't want to await them one by one in a loop—that's just sequential execution with extra steps. I'll use a ThrowingTaskGroup to fire these off in parallel.
extension ImageDownloader {
func fetchImages(from urls: [URL]) async throws -> [URL: UIImage] {
try await withThrowingTaskGroup(of: (URL, UIImage).self) { group in
for url in urls {
group.addTask {
let image = try await self.fetchImage(from: url)
return (url, image)
}
}
var results: [URL: UIImage] = [:]
for try await (url, image) in group {
results[url] = image
}
return results
}
}
}
Wait, I missed a critical detail
I just ran a test with a list of URLs that contained the same image multiple times. I noticed something annoying: my app was still making three separate network requests for the same URL if they were all started at the exact same time. Why? Because the first request hadn't finished and called cache.insert() before the second and third requests checked cache.image(for:).
To fix this, I need to cache the task, not just the result. This way, if a second request comes in for a URL that's already being downloaded, it can just await the existing task.
Here is the corrected ImageCache:
actor ImageCache {
// We store the Task, which will eventually produce the UIImage
private var cache: [URL: Task<UIImage, Error>] = [:]
func image(for url: URL) async throws -> UIImage {
// If there's already a task (running or finished), return its result
if let existingTask = cache[url] {
return try await existingTask.value
}
// Otherwise, create a new task to do the work
let task = Task {
// I'm passing the actual download logic here or calling a helper
// For brevity in this example, assume we handle the download inside the task
return try await downloadImage(url)
}
cache[url] = task
return try await task.value
}
private func downloadImage(_ url: URL) async throws -> UIImage {
let (data, _) = try await URLSession.shared.data(from: url)
guard let image = UIImage(data: data) else { throw URLError(.cannotDecodeContentData) }
return image
}
}
Now, even if you fire off ten requests for the same image simultaneously, the actor ensures that only one Task is created and stored. The other nine will simply wait for that first task to finish. Much cleaner.
📋 Practical Task
Exercise: Implementing a Concurrent Request Limit
In the current ImageDownloader, if you pass in 100 URLs, withThrowingTaskGroup will attempt to start 100 concurrent network requests. In a real-world production app, this can lead to timeouts or being throttled by the server.
Modify the fetchImages(from urls: [URL]) method to implement a "concurrency limit." Your goal is to ensure that no more than 4 images are being downloaded at any single moment. You'll need to manage how you add tasks to the group—perhaps by adding the first 4 and then adding a new one only after one of the previous tasks has completed.
There are no comments for now.