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()
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?