CachedAsyncImage is a SwiftUI view that loads and displays an image from a URL, using both in-memory and disk-based caching. It's optimized for performance and memory efficiency, designed to prevent unnecessary image reloads across sessions.
It is designed to work seamlessly with CustomImage, providing a robust image pipeline.
- Singleton class managing image caching
- Two-tier caching: memory (via
NSCache) and disk (viaFileManager) - Uses a custom
CacheImageWrapperto track memory cost and log evictions
- Swift actor responsible for tracking memory usage asynchronously
- Ensures accurate cost accounting when images are evicted
- Deduplicates fetches for the same URL
- Publishes the image state and failure flags
- Supports loading images via
URLSessionand promotes disk images into memory cache
struct CachedAsyncImage<Content: View, Placeholder: View>: View {
init(
url: URL,
@ViewBuilder content: @escaping (Image) -> Content,
@ViewBuilder placeholder: @escaping () -> Placeholder
)
}- Try to fetch from in-memory cache
- Fallback to disk cache if not found
- If not on disk, download via
URLSession - On success, store in both memory and disk
- If it fails, show placeholder
- 🧠 Memory usage tracking with total size limits
- 💾 Disk cache for persistence across launches
- 🔄 Automatic promotion of disk image to memory cache
- 🧪 Remote image validation using
NSDataDetector
CachedAsyncImage(url: URL(string: "https://example.com/image.png")!) { image in
image
.resizable()
} placeholder: {
ProgressView()
}CachedAsyncImage is the backend renderer for remote images used in the CustomImage component:
CustomImage.remote(
url: ...,
imageColor: ...,
placeholder: ...,
placeholderColor: ...
).view()👉 See the CustomImage Documentation for recommended usage and API details.
See also: CustomImage