Back to listSwift
Kingfisher-style Image Loading
Lv.51664@mukitaro0 playsJan 2, 2026
Kingfisher image loading pattern. Popular iOS image caching library.
preview.swift
1import UIKit2import Kingfisher3 4struct ImageOptions {5 var placeholder: UIImage?6 var transition: ImageTransition7 var cacheKey: String?8 var processor: ImageProcessor?9}10 11enum ImageTransition {12 case none13 case fade(TimeInterval)14 case flipFromLeft(TimeInterval)15 case flipFromRight(TimeInterval)16}17 18protocol ImageProcessor {19 func process(_ image: UIImage) -> UIImage20}21 22struct RoundCornerProcessor: ImageProcessor {23 let radius: CGFloat24 25 func process(_ image: UIImage) -> UIImage {26 UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)27 let rect = CGRect(origin: .zero, size: image.size)28 UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()29 image.draw(in: rect)30 let result = UIGraphicsGetImageFromCurrentImageContext()31 UIGraphicsEndImageContext()32 return result ?? image33 }34}35 36extension UIImageView {37 func setImage(with url: URL?, options: ImageOptions? = nil) {38 guard let url = url else {39 self.image = options?.placeholder40 return41 }42 43 if let placeholder = options?.placeholder {44 self.image = placeholder45 }46 47 // Async image loading with caching48 DispatchQueue.global().async {49 if let data = try? Data(contentsOf: url),50 var image = UIImage(data: data) {51 if let processor = options?.processor {52 image = processor.process(image)53 }54 DispatchQueue.main.async {55 self.image = image56 }57 }58 }59 }60}Custom problems are not included in rankings