Skip to content

Kingfisher

UI & GraphicsGraphics / Image ProcessingSwift

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.

SwiftUI loading
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()
downsampling decodes at the display size rather than full resolution. Without it, a list of 4000-pixel covers will exhaust memory on older devices.

Advanced usage

Where the library earns its place over a simpler alternative.

Cache configuration and prefetching
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)
Prefetching upcoming rows makes a scrolling gallery feel instant, and an explicit expiration stops the disk cache growing without bound.

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.