Image Loading and Caching

The interviewer asks

“How do you efficiently load and cache images?”

How to answer

I treat image loading as a pipeline with a cache at each expensive step: check an in-memory cache of decoded, display-sized images first; then the disk/HTTP cache (URLCache honoring server cache headers, or a custom disk cache); and only then the network. After download, decode and downsample off the main actor to the size the view needs, store the result in an NSCache with a cost, and hand it to the UI on the main actor. Two details separate a good answer: deduplicate in-flight requests for the same URL (an actor holding a dictionary of tasks), and cancel work when a cell is reused or a view disappears. In production many teams use Nuke, Kingfisher or SDWebImage, which implement this same pipeline.

Key points

  • Memory cache: NSCache (thread-safe, evicts under memory pressure) with totalCostLimit and per-image cost (pixel bytes)
  • Disk cache: URLCache with a sensible disk capacity, or a file cache in Caches/ for full control
  • Decode + downsample off main (byPreparingThumbnail(ofSize:) or ImageIO); cache the result
  • Shared state (in-flight map) lives in an actor; the loader is Sendable
  • SwiftUI AsyncImage: fine for simple cases; no in-memory cache or downsampling. iOS 27 adds .asyncImageURLSession(_:) so it loads through your own URLSession and cache configuration

If they dig deeper

Cache keys should include the target pixel size (the same URL may be shown as a thumbnail and full screen). An unstructured Task used for dedupe isn't cancelled when one caller cancels; real loaders reference-count waiters and cancel the download when the last one goes away. Prefetch with UICollectionViewDataSourcePrefetching / onScrollVisibilityChange and cancel prefetches for items scrolled past (see lazy-loading-strategy). Respond to memory warnings by clearing the memory cache (NSCache also evicts on its own). Disk caches count against the user's storage and need limits and cleanup. Formats: HEIC/AVIF/WebP decode costs differ; serving correctly sized images from a CDN beats any client-side trick.

Common pitfalls

Loading or decoding on the main thread. Caching Data or full-size images and resizing at display time. A [URL: UIImage] dictionary with no limit (abandoned memory). Firing duplicate downloads for the same URL in a fast-scrolling grid. Not cancelling on reuse, so images flash into the wrong cell. Ignoring HTTP cache headers.

How to use it

swift
import UIKit

actor ImageLoader {
    static let shared = ImageLoader()

    private let memory = NSCache<NSURL, UIImage>()            // auto-evicts under memory pressure
    private var inFlight: [URL: Task<UIImage, Error>] = [:]
    private let session: URLSession

    init(session: URLSession = .shared) {                     // URLCache handles the disk layer
        self.session = session
        memory.totalCostLimit = 100 * 1024 * 1024
    }

    func image(for url: URL, pointSize: CGSize, scale: CGFloat) async throws -> UIImage {
        if let cached = memory.object(forKey: url as NSURL) { return cached }
        if let running = inFlight[url] { return try await running.value }   // dedupe

        let task = Task {
            let (data, response) = try await session.data(from: url)
            guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.badServerResponse) }
            let pixels = CGSize(width: pointSize.width * scale, height: pointSize.height * scale)
            guard let image = await UIImage(data: data)?.byPreparingThumbnail(ofSize: pixels) else {
                throw URLError(.cannotDecodeContentData)
            }
            return image
        }
        inFlight[url] = task
        defer { inFlight[url] = nil }

        let image = try await task.value
        let cost = Int(image.size.width * image.scale * image.size.height * image.scale * 4)
        memory.setObject(image, forKey: url as NSURL, cost: cost)
        return image
    }
}

SwiftUI:

swift
import SwiftUI

struct Avatar: View {
    let url: URL
    var body: some View {
        AsyncImage(url: url) { image in
            image.resizable().scaledToFill()
        } placeholder: {
            Color.secondary.opacity(0.2)
        }
        .frame(width: 44, height: 44)
        .clipShape(.circle)
    }
}

@available(iOS 27, *)
struct Feed: View {
    let urls: [URL]
    let session: URLSession
    var body: some View {
        List(urls, id: \.self) { Avatar(url: $0) }
            .asyncImageURLSession(session)     // iOS 27+: AsyncImage loads through your session (and its URLCache)
    }
}

Best practices

  • Layer caches: memory (decoded, sized) → disk/HTTP → network
  • Downsample and decode off the main actor; cache the processed image with a cost
  • Deduplicate and cancel requests; tie work to cell reuse or SwiftUI .task lifetime
  • Bound every cache and clear the memory cache on memory warnings
  • Prefer a well-maintained library for complex feeds; know the pipeline it implements

Related concepts

  • Image downsampling, async image decoding, lazy loading strategy, NSCache, URLCache / response caching, actors, memory warnings