iOS: Kingfisher, Nuke and BlurHash Placeholders
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Baseline date: 2026-10-07. Check each library’s README for its current version and minimum iOS version before adopting it, since the SwiftUI APIs below have changed between major releases. The platform’s own capture, photo library and video APIs are in Camera, Media and Photos. This page is about loading, caching and placeholder rendering of remote images from a media backend, see responsive images and thumbnails.
AsyncImage and what it does not do
AsyncImage downloads a URL and shows a placeholder, then
the image, optionally with a custom phase handler and a transaction animation.
AsyncImage(url: coverURL) { phase in
switch phase {
case .success(let image): image.resizable().scaledToFill()
case .failure: Image(systemName: "photo")
default: ProgressView()
}
}
.frame(width: 160, height: 240)
.clipped()
It has no image cache of its own beyond the shared URLCache, so scrolling back through a list can download images again.
It offers no prefetching, no downsampling (a large file is decoded at full size, which costs memory), no control over
the cache or the request, and no support for a BlurHash placeholder beyond what you place in the closure. Use it for a
handful of small images. For lists and grids, use a library, or build on URLSession and ImageIO yourself.
Kingfisher
Kingfisher provides a memory and disk cache, processors and SwiftUI views.
import Kingfisher
import SwiftUI
struct CoverView: View {
let url: URL
let blurhash: String?
@Environment(\.displayScale) private var displayScale // UIScreen.main is deprecated since iOS 16
var body: some View {
KFImage(url)
.placeholder { BlurHashPlaceholder(hash: blurhash) }
.setProcessor(DownsamplingImageProcessor(size: CGSize(width: 160, height: 240)))
.scaleFactor(displayScale)
.cacheOriginalImage()
.fade(duration: 0.25)
.resizable()
.scaledToFill()
.frame(width: 160, height: 240)
.clipped()
}
}
DownsamplingImageProcessor uses ImageIO to decode the file straight to the target size, so a 1280 pixel image is never fully
decoded for a 160 point slot. scaleFactor makes the target size pixel-accurate on Retina screens, and it is read from the SwiftUI environment because
UIScreen.main is deprecated since iOS 16. Prefetch the next
page of covers with ImagePrefetcher(urls:).start(). Reference: Kingfisher
cheat sheet and the API documentation.
Nuke
Nuke separates the pipeline (ImagePipeline), the SwiftUI view (LazyImage in the NukeUI
module) and prefetching (ImagePrefetcher).
import Nuke
import NukeUI
import SwiftUI
struct CoverView: View {
let url: URL
let blurhash: String?
var body: some View {
LazyImage(request: ImageRequest(url: url, processors: [.resize(width: 160)])) { state in // points; Nuke applies the screen scale
if let image = state.image {
image.resizable().scaledToFill()
} else {
BlurHashPlaceholder(hash: blurhash)
}
}
.frame(width: 160, height: 240)
.clipped()
}
}
let prefetcher = ImagePrefetcher()
prefetcher.startPrefetching(with: nextPageURLs)
Nuke resizes in the pipeline, caches the decoded and the original data, and coalesces duplicate requests. Configure a larger
cache with ImagePipeline.Configuration (a DataCache for the disk), and share one pipeline. Reference:
Nuke documentation and the
README.
SDWebImage
SDWebImage is the long-established alternative, with an Objective-C core, the
SDWebImageSwiftUI package for SwiftUI (WebImage(url:)), and coder plugins for formats such as WebP and AVIF (for
older iOS versions that lack system support). Choose it if you already use it, or you need its coder plugins.
| Library | Choose it when |
|---|---|
|
Few small images, no caching needs. |
Kingfisher |
You want a mature, easy API with processors and a SwiftUI view. |
Nuke |
You want a pipeline you can configure and prefetch, and a small, modern API. |
SDWebImage |
You have existing usage, or need its extra codecs. |
Formats on Apple platforms
iOS and macOS decode JPEG, PNG, GIF, HEIC and, from iOS 14, WebP through ImageIO. AVIF decoding was added in iOS 16.
Check the ImageIO documentation for the exact versions and ask the API for
the format the device supports, as in the bestVariant helper of
the Android page, using #available(iOS 16, *).
BlurHash with the woltapp Swift implementation
The Swift implementation in the reference repository is meant to be
copied into the project. It adds an initialiser to UIImage:
struct BlurHashPlaceholder: View {
let hash: String?
var body: some View {
if let hash, let image = UIImage(blurHash: hash, size: CGSize(width: 32, height: 32), punch: 1) {
Image(uiImage: image).resizable().scaledToFill()
} else {
Color.gray.opacity(0.2)
}
}
}
Decode at 32 by 32 pixels (the initialiser renders a bitmap of exactly that size) and let SwiftUI scale it. Cache the decoded UIImage per hash (an NSCache), because the view
body can run many times, and never decode in body for a long list without that cache. The algorithm is in
the BlurHash page. The package also has an encoder, for when the
app computes the hash before an upload, see
device-side compression and uploads.
What happens between the URL and the pixels
Kingfisher and Nuke are two implementations of the same idea: look for the image in the cheapest place first, decode it once at the size that is shown, and keep the decoded result so that the next appearance of the cell costs nothing.
Three details of the diagram explain most surprises. The memory cache holds decoded bitmaps, so its limit is counted in
pixels times four bytes, not in file size. The disk cache holds encoded bytes, which is why cacheOriginalImage() in
Kingfisher matters: the processed (downsampled) result is cached under a key that includes the processor and its size,
so without the original a second size would download the file again. And requests for the same URL are coalesced, so ten
cells that appear at once cause one download.
Worked example: the cover grid on iOS
The running example is the cover b81f (2400 by 3600 pixels, the JSON of the
responsive images page). A tile is 160 by 240 points on
a 3x screen, which is 480 by 720 pixels. The first step is choosing the variant, in Swift and with the same rule as the
Android and React Native pages: the smallest variant at least as wide as the slot, in the best format that the device
decodes.
struct Variant: Decodable { let format: String; let width: Int; let url: URL }
struct Cover: Decodable { let id: String; let width: Int; let height: Int; let blurhash: String; let variants: [Variant] }
func bestVariant(_ variants: [Variant], pixelWidth: Int, formats: [String]) -> Variant? {
for format in formats {
let sorted = variants.filter { $0.format == format }.sorted { $0.width < $1.width }
if let hit = sorted.first(where: { $0.width >= pixelWidth }) ?? sorted.last { return hit }
}
return nil
}
func decodableFormats() -> [String] {
if #available(iOS 16, macOS 13, *) { return ["avif", "webp", "jpeg"] } // AVIF decoding arrived in iOS 16
return ["webp", "jpeg"]
}
This code was compiled and run with a cover JSON that has AVIF variants at 320, 640 and 1280 pixels, a WebP at 640 and JPEGs at 320 and 640. The results:
| Slot | Pixels wanted | Variant chosen |
|---|---|---|
160 pt at 2x |
320 |
|
160 pt at 3x |
480 |
|
400 pt at 3x |
1200 |
|
700 pt at 3x |
2100 |
|
160 pt at 3x, no AVIF decoder |
480 |
|
1000 px wanted, JPEG only |
1000 |
|
The last row is a reminder that the list may not contain a variant that is large enough in the format you can decode. The function then returns the largest one, and the image is scaled up by the view. If that looks soft on large screens, ask the backend to produce a bigger JPEG variant rather than serving the original.
The second step is the downsample of what was downloaded. The ImageIO call that Kingfisher’s processor makes was run on a synthetic 2400 by 3600 JPEG (the same function is printed on the page about device-side compression). Decoding at full size costs 32.96 MiB, and the thumbnail path costs a fraction:
| Thumbnail max pixel size | Result | Memory |
|---|---|---|
720 (the 160 by 240 pt tile at 3x) |
480 by 720 |
1.32 MiB |
1080 |
720 by 1080 |
2.97 MiB |
1920 |
1280 by 1920 |
9.38 MiB |
So a screen of 20 tiles at 480 by 720 holds 26 MiB of decoded images, where the same 20 decoded in full would hold 659 MiB,
which risks the app being terminated for memory on devices with little RAM. That arithmetic, not a measured speed-up, is why AsyncImage is
a poor fit for grids of large files.
Configuring the caches
Both libraries default to sensible limits, and the defaults should be replaced when you know the numbers. In Kingfisher the limits live on the cache objects:
import Kingfisher
func configureKingfisher() {
let cache = ImageCache.default
cache.memoryStorage.config.totalCostLimit = 120 * 1024 * 1024 // decoded images, in bytes
cache.memoryStorage.config.countLimit = 200
cache.diskStorage.config.sizeLimit = 300 * 1024 * 1024 // encoded files
cache.diskStorage.config.expiration = .days(14)
}
Nuke keeps the same two layers in its pipeline. A disk cache of encoded data is added with a configuration helper and the pipeline is shared by all views, so the limits apply to the whole app:
import Nuke
func configureNuke() {
var configuration = ImagePipeline.Configuration.withDataCache(name: "covers", sizeLimit: 300 * 1024 * 1024)
configuration.dataCachePolicy = .automatic // store originals and processed images as needed
ImagePipeline.shared = ImagePipeline(configuration: configuration)
}
The names of the Nuke options have changed between major versions (the data cache helper and the policy enumeration in
particular), so follow the documentation of the version that the project resolves. Nuke can also ask ImageIO for a
thumbnail instead of resizing a decoded image, through the thumbnail option on the request, which is the right choice
for large originals. Kingfisher does the same in DownsamplingImageProcessor.
A BlurHash decoder in Swift
The woltapp implementation is the one to copy into an app, but the decoder is small enough to read, and reading it shows why the placeholder costs almost nothing. The function below follows the algorithm of the BlurHash page and rejects a string whose length does not match its first character:
let alphabet = Array("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~")
let index: [Character: Int] = Dictionary(uniqueKeysWithValues: alphabet.enumerated().map { ($1, $0) })
func decode83(_ s: Substring) -> Int { s.reduce(0) { $0 * 83 + index[$1]! } }
func srgbToLinear(_ v: Int) -> Double { let x = Double(v) / 255; return x <= 0.04045 ? x / 12.92 : pow((x + 0.055) / 1.055, 2.4) }
func linearToSrgb(_ v: Double) -> Int { let x = max(0, min(1, v)); return Int((x <= 0.0031308 ? x * 12.92 : 1.055 * pow(x, 1 / 2.4) - 0.055) * 255 + 0.5) }
func signPow(_ v: Double, _ e: Double) -> Double { copysign(pow(abs(v), e), v) }
/// Returns width * height * 3 sRGB bytes, or nil if the hash is malformed.
func decodeBlurHash(_ hash: String, width: Int, height: Int, punch: Double = 1) -> [UInt8]? {
guard hash.count >= 6 else { return nil }
let h = Substring(hash)
let size = decode83(h.prefix(1))
let nx = size % 9 + 1, ny = size / 9 + 1
guard hash.count == 4 + 2 * nx * ny else { return nil }
let maxAC = Double(decode83(h.dropFirst(1).prefix(1)) + 1) / 166
var colors: [(Double, Double, Double)] = []
let dc = decode83(h.dropFirst(2).prefix(4))
colors.append((srgbToLinear(dc >> 16), srgbToLinear((dc >> 8) & 255), srgbToLinear(dc & 255)))
for i in 1..<(nx * ny) {
let v = decode83(h.dropFirst(4 + 2 * i).prefix(2))
let q = [v / (19 * 19), (v / 19) % 19, v % 19].map { signPow((Double($0) - 9) / 9, 2) * maxAC * punch }
colors.append((q[0], q[1], q[2]))
}
var out = [UInt8](repeating: 0, count: width * height * 3)
for y in 0..<height { for x in 0..<width {
var r = 0.0, g = 0.0, b = 0.0
for j in 0..<ny { for i in 0..<nx {
let basis = cos(Double.pi * Double(x * i) / Double(width)) * cos(Double.pi * Double(y * j) / Double(height))
let c = colors[i + j * nx]; r += c.0 * basis; g += c.1 * basis; b += c.2 * basis
} }
let o = (y * width + x) * 3
out[o] = UInt8(linearToSrgb(r)); out[o + 1] = UInt8(linearToSrgb(g)); out[o + 2] = UInt8(linearToSrgb(b))
} }
return out
}
Run on the hash of the running example, LKO2?U%2Tw=w]~RBVZRi};RPxuwH, the function reports 4 by 3 components and 28
characters (4 + 2 * 4 * 3), returns 3072 bytes for a 32 by 32 image with a mean colour of 208, 177, 162, and returns
nil for the same string without its last two characters. A thousand decodes at 32 by 32 took about 160 ms in an
optimised build on a Mac. That is cheap, and a phone is several times slower, so cache the result per hash all the same:
final class BlurHashCache {
static let shared = BlurHashCache()
private let cache = NSCache<NSString, UIImage>()
func image(for hash: String) -> UIImage? {
if let hit = cache.object(forKey: hash as NSString) { return hit }
guard let image = UIImage(blurHash: hash, size: CGSize(width: 32, height: 32)) else { return nil }
cache.setObject(image, forKey: hash as NSString)
return image
}
}
The UIImage(blurHash:size:) initialiser is the one of the woltapp package. A hash that fails to decode returns nil, and
the placeholder view above falls back to a flat grey, which is the correct behaviour for a missing or malformed hash.
Related pages
-
BlurHash in the Browser decodes the same hash on the web.