Skip to Content
Course content

239: Practice Exercise: Building a Concurrent Image Downloader with Caching

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.