What it is
Kingfisher downloads and caches images for Swift applications, with SwiftUI and UIKit integration, processors and prefetching.
KFImage in SwiftUI or kf extensions on UIImageView. Downloads are cached in memory and on disk, and cancelled when the view disappears.
Installation
.package(url: "https://github.com/onevcat/Kingfisher.git", from: "8.0.0")Getting started
The smallest useful thing you can do with it, and what each part means.
swift
KFImage(URL(string: book.coverURL))
.placeholder { ProgressView() }
.retry(maxCount: 3, interval: .seconds(2))
.downsampling(size: CGSize(width: 200, height: 300))
.cacheOriginalImage()
.fade(duration: 0.25)
.onFailure { error in print("load failed: \(error)") }
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 100, height: 150)
.clipped()Advanced usage
Where the library earns its place over a simpler alternative.
swift
let cache = ImageCache.default
cache.memoryStorage.config.totalCostLimit = 100 * 1024 * 1024 // 100 MB
cache.diskStorage.config.sizeLimit = 500 * 1024 * 1024
cache.diskStorage.config.expiration = .days(7)
// Warm the cache for rows about to scroll into view.
let prefetcher = ImagePrefetcher(urls: upcomingURLs)
prefetcher.start()
// Authenticated image endpoints.
let modifier = AnyModifier { request in
var r = request
r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
return r
}
KFImage(url).requestModifier(modifier)Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- Memory warnings while scrolling
- Images are decoded at full size. Add .downsampling(size:) and cap the memory cache.
- Images do not refresh after the server updates them
- The URL is the cache key. Add a version query parameter, or remove the key from the cache explicitly.
Best practices
- Always use downsampling for list thumbnails; full-resolution decoding causes most memory crashes.
- Set explicit memory and disk cache limits with an expiration.
- Prefetch upcoming items in long scrolling lists.
- Use a requestModifier for authenticated image URLs rather than embedding tokens in the URL.
Background
Why it exists, and what it was reacting to.
Kingfisher is the Swift equivalent of Glide or Coil, handling the memory and disk caching that a naive URLSession image loader gets wrong — particularly in fast-scrolling lists.
