How do I handle image caching in Combine with Swift?

Handling image caching in Combine with Swift involves using URLSession alongside Combine’s publisher and subscriber model. Here’s a basic example of how you can implement image caching to optimize your image loading performance in a Swift application. This method ensures that images are fetched from the cache when available, reducing network calls and improving user experience.

import Combine import UIKit class ImageLoader { private var cancellables = Set() private var imageCache = NSCache() func loadImage(from url: URL) -> AnyPublisher { if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) { return Just(cachedImage).eraseToAnyPublisher() } return URLSession.shared.dataTaskPublisher(for: url) .map { $0.data } .map(UIImage.init) .handleEvents(receiveOutput: { [weak self] image in if let image = image { self?.imageCache.setObject(image, forKey: url.absoluteString as NSString) } }) .replaceError(with: nil) .eraseToAnyPublisher() } } // Usage example let imageLoader = ImageLoader() let imageURL = URL(string: "https://example.com/image.png")! imageLoader.loadImage(from: imageURL) .sink(receiveValue: { image in // Update UI with the loaded image print(image) }) .store(in: &imageLoader.cancellables)

Swift Combine image caching URLSession iOS development