Loading images efficiently in SwiftUI can be achieved using the `AsyncImage` view. This component allows for asynchronous fetching of images and can be paired with caching strategies to enhance performance and reduce network load.
In this example, we'll explore how to use `AsyncImage` along with a simple caching mechanism. The caching can be implemented using a custom `ImageCache` class that stores images in memory.
import SwiftUI
// ImageCache Class
final class ImageCache {
private var cache = NSCache()
func get(for url: NSURL) -> UIImage? {
return cache.object(forKey: url)
}
func store(image: UIImage, for url: NSURL) {
cache.setObject(image, forKey: url)
}
}
struct AsyncImageView: View {
@State private var image: UIImage? = nil
let url: String
private let cache = ImageCache()
var body: some View {
Group {
if let image = image {
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
} else {
ProgressView()
.onAppear {
loadImage()
}
}
}
}
private func loadImage() {
guard let url = URL(string: url) else { return }
if let cachedImage = cache.get(for: url as NSURL) {
image = cachedImage
} else {
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, let fetchedImage = UIImage(data: data) else { return }
cache.store(image: fetchedImage, for: url as NSURL)
DispatchQueue.main.async {
image = fetchedImage
}
}.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?