SwiftUI KFImage notes

Just a few snippets to reference later when using Kingfisher library.

Published: Jan. 6, 2025
See books

This is not traditional “how to” blog post. I quite like the Kingfisher library and use it in multiple apps. However I often forget how exactly to arrange view modifiers in SwiftUI when using the KFImage component…

So I decided to create this with snippets that I am using so next time I can just check my blog (which I am used to doing) and grab a snippet or two.

It is entirely possible some of my usage isn’t optimal, but I found it to work reasonably well and I am not afraid to ship this code.

KFImage with placeholder, fade effect and fixed width + height:

KFImage(imageUrl)
            .fade(duration: 0.33)
            .placeholder { Image("placeholder").resizable() }
            .resizable()
            .frame(width: width, height: height)

Using the options from UIKit variant:

private func customKFImage(_ url: URL?) -> KFImage {
        let result = KFImage(url)
        result.options = KingfisherParsedOptionsInfo(
            KingfisherManager.shared.defaultOptions + [.forceTransition, .keepCurrentImageWhileLoading])
        return result
    }

I found this code somewhere and changed the options. Not super pretty, but I wasn’t able to find better option yet.

KFImage with aspect ratio:

KFImage.url(imageUrl)
            .resizable()
            .aspectRatio(16 / 9, contentMode: .fill)

 Using fallback image URL:

KFImage.url(video.thumbnailUrl)
            .alternativeSources([.network(video.fallbackThumbnailUrl)])

Probably quite specific, but useful for me when working with YouTube videos. Sometimes the good resolution thumbnail is not available and fallback is still better than generic placeholder.

Bluesky logo

Follow on Bluesky to not miss new posts

Filip Němeček profile photo

WRITTEN BY

Filip Němeček Mastodon

iOS blogger and developer with interest in Python/Django.

iOS blogger and developer with interest in Python/Django.