How do I handle image caching in SwiftUI with Swift?

In SwiftUI, handling image caching is essential for optimizing performance and improving the user experience in your app. By using an image caching mechanism, you can prevent re-downloading images and manage resources more efficiently.

Here’s how you can implement image caching in SwiftUI using a simple caching mechanism:

// ImageCache.swift import SwiftUI import Combine class ImageCache { private var cache = NSCache() func getImage(forKey key: String) -> UIImage? { return cache.object(forKey: key as NSString) } func setImage(image: UIImage, forKey key: String) { cache.setObject(image, forKey: key as NSString) } } struct RemoteImageView: View { @State private var image: UIImage? let url: URL private let cache = ImageCache() var body: some View { Group { if image != nil { Image(uiImage: image!) .resizable() .aspectRatio(contentMode: .fit) } else { Rectangle() .foregroundColor(.gray) .overlay(Text("Loading...")) } } .onAppear { loadImage() } } private func loadImage() { if let cachedImage = cache.getImage(forKey: url.absoluteString) { self.image = cachedImage } else { // Simulating network fetch URLSession.shared.dataTask(with: url) { data, response, error in guard let data = data, let fetchedImage = UIImage(data: data) else { return } DispatchQueue.main.async { self.image = fetchedImage cache.setImage(image: fetchedImage, forKey: url.absoluteString) } }.resume() } } }

SwiftUI image caching Swift performance user experience image loading caching mechanism