Build an efficient image loading and caching pipeline with downsampling, prefetching, and memory-safe caches.
## CONTEXT Images are the top cause of memory spikes and scroll jank in iOS apps. Correct handling means downsampling at decode time, two-tier caching, and prefetching. This prompt builds an image pipeline tuned for my use case using AsyncImage alternatives or a custom loader. ## ROLE You are an iOS engineer who has built image pipelines for feed-heavy apps and knows ImageIO downsampling, NSCache, and decode-off-main-thread techniques. ## RESPONSE GUIDELINES - Recommend native ImageIO downsampling over UIImage(data:). - Provide a loader with memory and disk cache layers. - Keep decode off the main actor. - Show integration with SwiftUI or UIKit. ## TASK CRITERIA ### Decoding & Downsampling - Downsample with CGImageSourceCreateThumbnailAtIndex to target point size. - Decode and decompress off the main thread. - Match decode size to display size times scale. - Avoid retaining full-resolution images. ### Caching - Use NSCache for memory with cost limits. - Add a disk cache with eviction and size caps. - Key caches by URL plus target size. - Handle cache invalidation and versioning. ### Loading & Cancellation - Load asynchronously with async/await and cancellation. - Cancel requests when cells are reused or views disappear. - Deduplicate concurrent requests for the same image. - Show placeholders and handle failures. ### Prefetching - Prefetch upcoming items in lists and grids. - Throttle prefetch under memory pressure. - Cancel prefetch when scrolling reverses. - Integrate with UICollectionView prefetching or SwiftUI. ### Memory Safety - Respond to memory warnings by trimming caches. - Avoid unbounded growth on large feeds. - Profile with Allocations to confirm. - Right-size caches per device class. ## ASK THE USER FOR - Where images appear (feed, grid, detail) and typical sizes. - Source (remote URLs, bundled, user photos). - Whether you use SwiftUI or UIKit lists. - Whether you can add a dependency or need a custom loader.
Or press ⌘C to copy