### Install Dependencies and Run Tests (Bash) Source: https://github.com/onevcat/kingfisher/blob/master/README-LLM.md This command installs project dependencies using Bundler and then executes all automated tests for the Kingfisher library. ```bash bundle install && bundle exec fastlane tests ``` -------------------------------- ### Troubleshooting Bundle Install Failures (Bash) Source: https://github.com/onevcat/kingfisher/blob/master/docs/build-system.md Provides commands to resolve 'bundle install' failures by updating bundler or installing with a specific version. This is useful when dependency conflicts arise during project setup. ```bash # Update bundler gem install bundler # Install with specific bundler version bundle _2.x.x_ install ``` -------------------------------- ### Advanced Image Processing and Configuration Source: https://github.com/onevcat/kingfisher/blob/master/README.md An advanced example showing how to apply image processors like downsampling and rounding, configure placeholders and indicators, and handle completion results with success or failure cases. ```swift let url = URL(string: "https://example.com/high_resolution_image.png") let processor = DownsamplingImageProcessor(size: imageView.bounds.size) |> RoundCornerImageProcessor(cornerRadius: 20) imageView.kf.indicatorType = .activity imageView.kf.setImage( with: url, placeholder: UIImage(named: "placeholderImage"), options: [ .processor(processor), .scaleFactor(UIScreen.main.scale), .transition(.fade(1)), .cacheOriginalImage ]) { result in switch result { case .success(let value): print("Task done for: \(value.source.url?.absoluteString ?? "")") case .failure(let error): print("Job failed: \(error.localizedDescription)") } } ``` -------------------------------- ### Troubleshooting Simulator Not Found (Bash) Source: https://github.com/onevcat/kingfisher/blob/master/docs/build-system.md Guides users on how to list available simulators and update destination strings when a simulator is not found. This helps in running tests on the correct simulated device. ```bash # List available simulators xcrun simctl list devices # Update destination string accordingly ``` -------------------------------- ### Install Carthage and Integrate Kingfisher Source: https://github.com/onevcat/kingfisher/wiki/Installation-Guide Commands and configuration for managing Kingfisher dependencies using the Carthage decentralized dependency manager. ```bash brew update brew install carthage ``` ```ogdl github "onevcat/Kingfisher" ~> 7.0 ``` ```bash carthage update Kingfisher --platform iOS ``` -------------------------------- ### Set Local Low Data Mode Image Source (Swift) Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/Topics/Topic_LowDataMode.md This example shows how to use a local file as the low-data image source. This approach avoids network downloads entirely, making it suitable for restrictive network conditions or when offline. ```swift imageView.kf.setImage( with: highResolutionURL, options: [ .lowDataSource( .provider(LocalFileImageDataProvider(fileURL: localFileURL))) ] ) ``` -------------------------------- ### Prefetch Images with ImagePrefetcher Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/Topics/Topic_Prefetch.md Demonstrates how to use ImagePrefetcher to preload a list of image URLs. It initializes the prefetcher with URLs and starts the prefetching process. The completion handler reports which resources were successfully prefetched. This is useful for proactively loading images that are likely to be displayed soon. ```swift let urls = [ "https://example.com/image1.jpg", "https://example.com/image2.jpg" ].map { URL(string: $0)! } let prefetcher = ImagePrefetcher(urls: urls) { skippedResources, failedResources, completedResources in print("These resources are prefetched: \(completedResources)") } prefetcher.start() // Later when you need to display these images: imag eView.kf.setImage(with: urls[0]) anotherImageView.kf.setImage(with: urls[1]) ``` -------------------------------- ### Manual Installation via Git Submodule Source: https://github.com/onevcat/kingfisher/wiki/Installation-Guide Commands to manually add Kingfisher as a git submodule and checkout a specific stable version. ```bash git submodule add https://github.com/onevcat/Kingfisher.git cd Kingfisher && git checkout 7.0.0 ``` -------------------------------- ### Setting Images for UI Components with Kingfisher (Swift) Source: https://github.com/onevcat/kingfisher/blob/master/docs/development.md Provides examples of how to set images for `UIImageView` and `NSImageView` using Kingfisher. It showcases basic usage with URLs, advanced configuration with options and completion handlers, and a builder pattern approach for fluent image loading. ```swift // Basic usage imageView.kf.setImage(with: url) // With configuration imageView.kf.setImage( with: url, placeholder: placeholderImage, options: [.transition(.fade(0.2)), .cacheMemoryOnly], completionHandler: { result in // Handle result } ) ``` ```swift KF.url(imageURL) .placeholder(placeholderImage) .fade(duration: 0.2) .cacheMemoryOnly() .onSuccess { result in print("Image loaded: \(result.image)") } .set(to: imageView) ``` -------------------------------- ### Load Local File Image with Kingfisher Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/Topics/Topic_ImageDataProvider.md Demonstrates using LocalFileImageDataProvider to load an image from a local file URL, with an optional example of applying an image processor. ```swift let url = URL(fileURLWithPath: path) let provider = LocalFileImageDataProvider(fileURL: url) imageView.kf.setImage(with: provider) let processor = RoundCornerImageProcessor(cornerRadius: 20) imageView.kf.setImage(with: provider, options: [.processor(processor)]) ``` -------------------------------- ### Automate Build and Test with Fastlane Source: https://github.com/onevcat/kingfisher/blob/master/docs/build-system.md Common Fastlane commands to run tests, build for CI, and lint project configurations. Requires Ruby dependencies to be installed via bundle. ```bash bundle install bundle exec fastlane tests DESTINATION="platform=iOS Simulator,name=iPhone 15,OS=17.5" bundle exec fastlane build_ci DESTINATION="platform=macOS" bundle exec fastlane test_ci bundle exec fastlane build destination:"platform=iOS Simulator,name=iPhone 15" bundle exec fastlane lint ``` -------------------------------- ### Configuring KFImage Lifecycle and Placeholders Source: https://github.com/onevcat/kingfisher/wiki/SwiftUI-Support Illustrates how to add placeholders during download, configure retry logic, and handle success or failure callbacks. ```swift KFImage(url) .placeholder { Image(systemName: "arrow.2.circlepath.circle") .font(.largeTitle) .opacity(0.3) } .retry(maxCount: 3, interval: .seconds(5)) .onSuccess { r in print("success: \(r)") } .onFailure { e in print("failure: \(e)") } ``` -------------------------------- ### Configure Cache Storage Limits Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/CommonTasks/CommonTasks_Cache.md Shows how to set memory and disk storage limits, including total cost and count limits for memory, and size limits for disk. ```swift cache.memoryStorage.config.totalCostLimit = 300 * 1024 * 1024 cache.memoryStorage.config.countLimit = 150 cache.diskStorage.config.sizeLimit = 1000 * 1024 * 1024 ``` -------------------------------- ### Kingfisher Installation with CocoaPods (Ruby) Source: https://github.com/onevcat/kingfisher/blob/master/README.md Provides the necessary configuration to install Kingfisher version 8.0.0 using CocoaPods. This snippet specifies the source repository, target platform, and framework usage, ensuring compatibility with iOS 13.0 and later. ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '13.0' use_frameworks! target 'MyApp' do pod 'Kingfisher', '~> 8.0' end ``` -------------------------------- ### GET /image/animated Source: https://github.com/onevcat/kingfisher/wiki/Cheat-Sheet Handles loading of animated images such as GIFs with options to control frame decoding. ```APIDOC ## GET /image/animated ### Description Retrieves and displays an animated GIF image, with support for first-frame-only rendering. ### Method GET ### Endpoint /image/animated ### Parameters #### Query Parameters - **url** (string) - Required - The URL of the GIF image. - **onlyLoadFirstFrame** (boolean) - Optional - If true, displays only the first frame of the animation. ### Request Example { "url": "https://example.com/animation.gif", "onlyLoadFirstFrame": false } ### Response #### Success Response (200) - **format** (string) - The detected image format. #### Response Example { "format": "gif" } ``` -------------------------------- ### Build and Test with Swift Package Manager Source: https://github.com/onevcat/kingfisher/blob/master/docs/build-system.md Commands to build, test, and manage the project using the Swift Package Manager CLI. These commands are essential for local development and verifying package integrity. ```bash swift build swift build -Xswiftc -swift-version -Xswiftc 5 swift build -c release swift test swift package generate-xcodeproj ``` -------------------------------- ### Install Nocilla via CocoaPods Source: https://github.com/onevcat/kingfisher/blob/master/Tests/Dependency/Nocilla/README.md Add the Nocilla dependency to your project using the CocoaPods package manager. ```ruby pod 'Nocilla' ``` -------------------------------- ### Install CocoaPods and Integrate Kingfisher Source: https://github.com/onevcat/kingfisher/wiki/Installation-Guide Commands and configuration for managing Kingfisher dependencies using the CocoaPods package manager. ```bash gem install cocoapods ``` ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '12.0' use_frameworks! target 'MyApp' do pod 'Kingfisher', '~> 7.0' end ``` ```bash pod install ``` -------------------------------- ### ImageCache Configuration and Usage Source: https://github.com/onevcat/kingfisher/blob/master/docs/development.md Demonstrates how to initialize a custom `ImageCache`, configure memory and disk storage limits, and use it with Kingfisher's image loading methods. It also shows how to perform manual cache operations like storing and retrieving images. ```APIDOC ## ImageCache Configuration and Usage ### Description This section covers the initialization, configuration, and basic usage of the `ImageCache` class in Kingfisher. It includes setting memory and disk limits, using a custom cache with image loading, and performing manual cache operations. ### Method N/A (Configuration and Usage Example) ### Endpoint N/A (Code Example) ### Parameters N/A ### Request Example ```swift // Configure cache let cache = ImageCache(name: "custom") cache.memoryStorage.config.totalCostLimit = 50 * 1024 * 1024 // 50MB cache.diskStorage.config.sizeLimit = 200 * 1024 * 1024 // 200MB // Use with options imageView.kf.setImage(with: url, options: [.targetCache(cache)]) // Manual cache operations cache.store(image, forKey: key) cache.retrieveImage(forKey: key) { result in // Handle cached image } ``` ### Response N/A (Code Example) ### Response Example N/A ``` -------------------------------- ### Setting Image with URL (UIKit) Source: https://context7.com/onevcat/kingfisher/llms.txt Demonstrates how to use the `kf` extension on `UIImageView` to download, cache, and display images from a URL. Includes basic usage, options for placeholders and completion handlers, and how to cancel downloads. ```APIDOC ## Setting Image with URL (UIKit) ### Description Use the `kf` extension on `UIImageView` to download, cache, and display images from a URL. This method handles asynchronous downloading and caching automatically. ### Method `UIImageView.kf.setImage(with:options:progressBlock:completionHandler:)` ### Endpoint N/A (This is a library method, not a network endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import Kingfisher let url = URL(string: "https://example.com/image.png")! imageView.kf.setImage(with: url) // With placeholder and completion handler let placeholderImage = UIImage(named: "placeholder") imageView.kf.setImage( with: url, placeholder: placeholderImage, options: [ .transition(.fade(0.3)), .cacheOriginalImage ], progressBlock: { receivedSize, totalSize in let progress = Float(receivedSize) / Float(totalSize) print("Download progress: \(progress)") }, completionHandler: { result in switch result { case .success(let value): print("Image: \(value.image)") print("Cache type: \(value.cacheType)") // .none, .memory, or .disk print("Source: \(value.source)") case .failure(let error): print("Error: \(error.localizedDescription)") } } ) // Cancel download if needed imag eView.kf.cancelDownloadTask() ``` ### Response #### Success Response (200) - **image** (UIImage) - The downloaded and cached image. - **cacheType** (ImageCacheType) - Indicates if the image was retrieved from memory, disk, or not found. - **source** (ImageSource) - The source from which the image was loaded. #### Response Example ```json { "image": "UIImage object", "cacheType": "disk", "source": "URL: https://example.com/image.png" } ``` ``` -------------------------------- ### Basic Image Loading in UIKit and SwiftUI Source: https://github.com/onevcat/kingfisher/wiki/Getting-Started-with-Kingfisher Demonstrates the simplest way to load an image from a URL into a UIImageView using the Kingfisher extension and how to display an image in a SwiftUI view using KFImage. ```swift import Kingfisher // UIKit let url = URL(string: "https://example.com/image.png") imageView.kf.setImage(with: url) // SwiftUI var body: some View { KFImage(URL(string: "https://example.com/image.png")!) } ``` -------------------------------- ### Initialize Nocilla in Kiwi Specs Source: https://github.com/onevcat/kingfisher/blob/master/Tests/Dependency/Nocilla/README.md Configure the Nocilla lifecycle within a Kiwi test suite to start, stop, and clear stubs between test cases. ```objective-c #import "Kiwi.h" #import "Nocilla.h" SPEC_BEGIN(ExampleSpec) beforeAll(^{ [[LSNocilla sharedInstance] start]; }); afterAll(^{ [[LSNocilla sharedInstance] stop]; }); afterEach(^{ [[LSNocilla sharedInstance] clearStubs]; }); it(@"should do something", ^{ // Stub here! }); SPEC_END ``` -------------------------------- ### Custom Cache Instance Usage Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/CommonTasks/CommonTasks_Cache.md Shows how to initialize a custom ImageCache with a specific name and apply it to an image request. ```swift let cache = ImageCache(name: "my-own-cache") imageView.kf.setImage(with: url, options: [.targetCache(cache)]) ``` -------------------------------- ### Method Chaining with KF Builder Source: https://github.com/onevcat/kingfisher/wiki/Getting-Started-with-Kingfisher Compares the standard extension approach with the fluent KF builder pattern for complex image loading configurations, including progress tracking and completion handlers. ```swift // Use `kf` extension imageView.kf.setImage( with: url, placeholder: placeholderImage, options: [ .processor(processor), .loadDiskFileSynchronously, .cacheOriginalImage, .transition(.fade(0.25)), .lowDataMode(.network(lowResolutionURL)) ], progressBlock: { receivedSize, totalSize in }, completionHandler: { result in } ) // Use `KF` builder KF.url(url) .placeholder(placeholderImage) .setProcessor(processor) .loadDiskFileSynchronously() .cacheMemoryOnly() .fade(duration: 0.25) .lowDataModeSource(.network(lowResolutionURL)) .onProgress { receivedSize, totalSize in } .onSuccess { result in } .onFailure { error in } .set(to: imageView) ``` -------------------------------- ### Swift Builder Pattern for URL Source: https://github.com/onevcat/kingfisher/blob/master/docs/development.md Implements the builder pattern for creating image download configurations, starting with a URL. It allows for fluent configuration of options like placeholders. ```swift public enum KF { /// Creates a builder for a given URL public static func url(_ url: URL?, cacheKey: String? = nil) -> KF.Builder { source(url?.convertToSource(overrideCacheKey: cacheKey)) } } extension KF { public class Builder: @unchecked Sendable { private let source: Source? private var _options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions) // Fluent configuration methods public func placeholder(_ image: KFCrossPlatformImage?) -> Self { self.placeholder = image return self } } } ``` -------------------------------- ### Kingfisher Options Pattern Implementation (Swift) Source: https://github.com/onevcat/kingfisher/blob/master/docs/development.md Demonstrates the implementation of a comprehensive options system using Swift enums and structs. It defines available option items and a parsed structure for internal use, handling various configurations for image downloading and processing. ```swift /// Represents the available option items public enum KingfisherOptionsInfoItem: Sendable { case targetCache(ImageCache) case downloader(ImageDownloader) case transition(ImageTransition) case downloadPriority(Float) case forceRefresh case processor(any ImageProcessor) // ... many more options } /// Parsed options for internal use public struct KingfisherParsedOptionsInfo: Sendable { public var targetCache: ImageCache? = nil public var downloader: ImageDownloader? = nil public var transition: ImageTransition = .none // ... corresponding properties public init(_ info: KingfisherOptionsInfo?) { guard let info = info else { return } for option in info { switch option { case .targetCache(let value): targetCache = value case .downloader(let value): downloader = value // ... handle all options } } } } ``` -------------------------------- ### Install Kingfisher with CocoaPods Source: https://github.com/onevcat/kingfisher/wiki/Getting-Started-with-Kingfisher This snippet shows how to add Kingfisher version 7.0 or later to your iOS project using CocoaPods. Ensure you have the CocoaPods repository sourced and specify the platform and framework settings. ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '12.0' use_frameworks! target 'MyApp' do pod 'Kingfisher', '~> 7.0' end ``` -------------------------------- ### Loading Images with Custom Sources and Options Source: https://github.com/onevcat/kingfisher/wiki/SwiftUI-Support Demonstrates how to load images using custom resources (like specific cache keys) and apply Kingfisher-specific options like downsampling. ```swift var resource: Resource { ImageResource(downloadURL: self.url!, cacheKey: "my_cache_key") } KFImage(source: .network(resource)) .downsampling(size: CGSize(width: 50, height: 50)) .retry(maxCount: 3, interval: .seconds(5)) .cacheOriginalImage() ``` -------------------------------- ### Use Default ImageProcessor Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/CommonTasks/CommonTasks_Processor.md Demonstrates how to use the default ImageProcessor, which converts downloaded data into an image object. It supports PNG, JPEG, and GIF formats. This is equivalent to not specifying any processor. ```swift imageView.kf.setImage(with: url) // It equals to imageView.kf.setImage(with: url, options: [.processor(DefaultImageProcessor.default)]) ``` -------------------------------- ### Run All Kingfisher Tests with Fastlane Source: https://github.com/onevcat/kingfisher/blob/master/docs/testing.md This command installs dependencies and executes all Kingfisher tests across various platforms using the Fastlane tool. It's the primary method for running the comprehensive test suite. ```bash bundle install bundle exec fastlane tests ``` -------------------------------- ### Loading and Displaying Live Photos with Kingfisher Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/Topics/Topic_LivePhoto.md This sequence shows how to initialize a PHLivePhotoView, define the URLs for the image and video components, and use Kingfisher's kf.setImage extension to load the Live Photo. ```swift import Kingfisher import PhotosUI // Initialize view let livePhotoView = PHLivePhotoView(frame: CGRect(x: 0, y: 0, width: 300, height: 300)) view.addSubview(livePhotoView) // Prepare URLs let imageURL = URL(string: "https://example.com/image.heic")! let videoURL = URL(string: "https://example.com/video.mov")! let urls = [imageURL, videoURL] // Load the Live Photo livePhotoView.kf.setImage(with: urls) { result in switch result { case .success(let retrieveResult): print("Live photo loaded: \(retrieveResult.livePhoto)") case .failure(let error): print("Error: \(error)") } } ``` -------------------------------- ### Set Cache Expiration Policies Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/CommonTasks/CommonTasks_Cache.md Demonstrates how to configure default expiration times for memory and disk storage, and how to override them for specific requests. ```swift cache.memoryStorage.config.expiration = .seconds(600) cache.diskStorage.config.expiration = .never imageView.kf.setImage(with: url, options: [.memoryCacheExpiration(.never)]) cache.memoryStorage.config.cleanInterval = 30 ``` -------------------------------- ### Troubleshooting Xcode Version Mismatch (Bash) Source: https://github.com/onevcat/kingfisher/blob/master/docs/build-system.md Offers solutions for Xcode version conflicts, allowing explicit setting of the Xcode version for Fastlane commands or using 'xcode-select' to manage the active Xcode installation. ```bash # Set Xcode version explicitly XCODE_VERSION=16.2 bundle exec fastlane tests # Or use xcode-select sudo xcode-select -s /Applications/Xcode_16.2.app ``` -------------------------------- ### Run Kingfisher Tests with Xcode Source: https://github.com/onevcat/kingfisher/blob/master/docs/testing.md This command demonstrates how to initiate the Kingfisher test suite using the xcodebuild command-line tool. It requires opening the workspace and specifying the scheme and destination. ```bash xcodebuild test -workspace Kingfisher.xcworkspace -scheme Kingfisher -destination "platform=iOS Simulator,name=iPhone 15" ``` -------------------------------- ### Modify Download Request with Kingfisher Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/CommonTasks/CommonTasks_Downloader.md Shows how to modify an outgoing download request, for example, by adding custom headers like an 'Access-Token'. This is useful for secured resources. The modifier can also be applied to view extensions. ```swift let modifier = AnyModifier { request in var r = request r.setValue("abc", forHTTPHeaderField: "Access-Token") return r } downloader.downloadImage(with: url, options: [.requestModifier(modifier)]) { result in // ... } // This option also works for view extension methods. imageView.kf.setImage(with: url, options: [.requestModifier(modifier)]) ``` -------------------------------- ### Fastlane Build and Test Commands Source: https://github.com/onevcat/kingfisher/blob/master/CLAUDE.md Automates the build and testing process for the Kingfisher project across multiple platforms using Fastlane. Includes commands for dependency installation, running all tests, platform-specific tests, building, and linting. ```bash bundle install bundle exec fastlane tests bundle exec fastlane test destination:"platform=iOS Simulator,name=iPhone 16" bundle exec fastlane build destination:"platform=iOS Simulator,name=iPhone 16" bundle exec fastlane lint ``` -------------------------------- ### Replacing a Request Stub Source: https://github.com/onevcat/kingfisher/blob/master/Tests/Dependency/Nocilla/README.md This example shows how to dynamically change the response of a previously stubbed request. By calling `stubRequest` again with the same URL and method, you can override the existing stub with a new response, useful for testing different scenarios sequentially. ```objc stubRequest(@"POST", @"https://api.example.com/authorize/"). andReturn(401); // Some test expectation... stubRequest(@"POST", @"https://api.example.com/authorize/"). andReturn(200); ``` -------------------------------- ### Instantiate ColorElement as a Struct in Swift Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/MigrationGuide/Migration-To-8.md This code demonstrates the change in how `Filter.ColorElement` is instantiated. Previously a typealias for a tuple, it is now a struct. The example shows the old tuple-based initialization and the new, recommended struct initialization using its designated initializer. ```swift let brightness, contrast, saturation, inputEV: CGFloat // Old let colorElement: Filter.ColorElement = (brightness, contrast, saturation, inputEV) // New let colorElement = Filter.ColorElement(brightness, contrast, saturation, inputEV) ``` -------------------------------- ### Chain Multiple Image Processors Source: https://github.com/onevcat/kingfisher/wiki/Cheat-Sheet Demonstrates how to combine multiple processors using the pipe operator to apply sequential image transformations. ```swift let processor = BlurImageProcessor(blurRadius: 4) |> RoundCornerImageProcessor(cornerRadius: 20) imageView.kf.setImage(with: url, options: [.processor(processor)]) ``` -------------------------------- ### Customize Cache Key for ImageResource Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/CommonTasks/CommonTasks_Cache.md Demonstrates how to create an ImageResource with a custom cache key instead of using the default URL-based key. ```swift let resource = ImageResource(downloadURL: url, cacheKey: "my_cache_key") imageView.kf.setImage(with: resource) ``` -------------------------------- ### Configure Image Loading Indicators Source: https://github.com/onevcat/kingfisher/wiki/Cheat-Sheet Set up visual feedback during image downloads using either a static image or a custom UIView implementation. This provides a better user experience during network operations. ```swift let path = Bundle.main.path(forResource: "loader", ofType: "gif")! let data = try! Data(contentsOf: URL(fileURLWithPath: path)) imageView.kf.indicatorType = .image(imageData: data) imageView.kf.setImage(with: url) struct MyIndicator: Indicator { let view: UIView = UIView() func startAnimatingView() { view.isHidden = false } func stopAnimatingView() { view.isHidden = true } init() { view.backgroundColor = .red } } let i = MyIndicator() imageView.kf.indicatorType = .custom(indicator: i) ``` -------------------------------- ### Creating a Custom Cache Serializer in Kingfisher Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/CommonTasks/CommonTasks_Serializer.md Provides an example of creating a custom CacheSerializer by conforming to the CacheSerializer protocol. This involves implementing the `data(with:original:)` and `image(with:options:)` methods to define custom serialization and deserialization logic for image caching. ```swift struct MyCacheSerializer: CacheSerializer { func data(with image: Image, original: Data?) -> Data? { return MyFramework.data(of: image) } func image(with data: Data, options: KingfisherParsedOptionsInfo?) -> Image? { return MyFramework.createImage(from: data) } } let serializer = MyCacheSerializer() let url = URL(string: "https://yourdomain.com/example.png") imageView.kf.setImage(with: url, options: [.cacheSerializer(serializer)]) ``` -------------------------------- ### Creating an ImageProcessor from CIFilter Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/CommonTasks/CommonTasks_Processor.md Demonstrates how to quickly create an ImageProcessor from a Core Image Filter (CIFilter). This involves defining a struct that conforms to `CIImageProcessor` and providing a `filter` closure that applies the CIFilter to the input image. ```swift struct MyCIFilter: CIImageProcessor { let identifier = "com.yourdomain.myCIFilter" let filter = Filter { input in guard let filter = CIFilter(name: "xxx") else { return nil } filter.setValue(input, forKey: kCIInputBackgroundImageKey) return filter.outputImage } } ``` -------------------------------- ### Creating a Custom ImageProcessor Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/CommonTasks/CommonTasks_Processor.md Explains how to create a custom ImageProcessor by conforming to the `ImageProcessor` protocol. This involves implementing the `identifier` and `process` methods. The `identifier` is crucial for cache key generation, and the `process` method handles the image transformation from either an `Image` or `Data` input. ```swift struct MyProcessor: ImageProcessor { let someValue: Int var identifier: String { "com.yourdomain.myprocessor-\(someValue)" } // Convert input data/image to target image and return it. func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? { switch item { case .image(let image): // A previous processor already converted the image to an image object. // You can do whatever you want to apply to the image and return the result. return image case .data(let data): // Your own way to convert some data to an image. return createAnImage(data: data) } } } let processor = MyProcessor(someValue: 10) let url = URL(string: "https://example.com/my_image.png") imageView.kf.setImage(with: url, options: [.processor(processor)]) ``` -------------------------------- ### Built-in ImageProcessors in Kingfisher Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/CommonTasks/CommonTasks_Processor.md Provides examples of various built-in ImageProcessors available in Kingfisher for common image transformations. These include rounding corners, downsampling, cropping, blurring, overlaying colors, tinting, adjusting color controls, black and white conversion, blending, and compositing. ```swift // Round corner let processor = RoundCornerImageProcessor(cornerRadius: 20) // Downsampling let processor = DownsamplingImageProcessor(size: CGSize(width: 100, height: 100)) // Cropping let processor = CroppingImageProcessor(size: CGSize(width: 100, height: 100), anchor: CGPoint(x: 0.5, y: 0.5)) // Blur let processor = BlurImageProcessor(blurRadius: 5.0) // Overlay with a color & fraction let processor = OverlayImageProcessor(overlay: .red, fraction: 0.7) // Tint with a color let processor = TintImageProcessor(tint: .blue) // Adjust color let processor = ColorControlsProcessor(brightness: 1.0, contrast: 0.7, saturation: 1.1, inputEV: 0.7) // Black & White let processor = BlackWhiteProcessor() // Blend (iOS) let processor = BlendImageProcessor(blendMode: .darken, alpha: 1.0, backgroundColor: .lightGray) // Compositing let processor = CompositingImageProcessor(compositingOperation: .darken, alpha: 1.0, backgroundColor: .lightGray) // Use the process in view extension methods. imageView.kf.setImage(with: url, options: [.processor(processor)]) ``` -------------------------------- ### Configure Synchronous Disk Loading Source: https://github.com/onevcat/kingfisher/wiki/Cheat-Sheet Demonstrates how to force synchronous disk file loading to prevent flickering in UI elements like table views. This is achieved by passing the .loadDiskFileSynchronously option to the Kingfisher options array. ```swift let options: [KingfisherOptionsInfo]? = isReloading ? [.loadDiskFileSynchronously] : nil imageView.kf.set(with: image, options: options) ``` -------------------------------- ### Update DownloadTask Initialization and Validation in Swift Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/MigrationGuide/Migration-To-8.md This snippet illustrates the change in `DownloadTask` from a struct to a class. It highlights how methods returning `DownloadTask` now return non-optional values. The example also shows the updated method for checking if a download task is initialized, changing from checking for `nil` to using the `isInitialized` property. ```swift // old open func downloadImage( with url: URL, options: KingfisherParsedOptionsInfo, completionHandler: (@Sendable (Result) -> Void)? = nil ) -> DownloadTask? // new open func downloadImage( with url: URL, options: KingfisherParsedOptionsInfo, completionHandler: (@Sendable (Result) -> Void)? = nil ) -> DownloadTask ``` ```swift // old let downloadTask: DownloadTask? = downloader.downloadImage(with: url, options: options) func doSomethingWithTask() { if let task = downloadTask { // Do something with the task, for example, cancel it } } // new let downloadTask: DownloadTask = downloader.downloadImage(with: url, options: options) func doSomethingWithTask() { if downloadTask.isInitialized { // Do something with the task, for example, cancel it } } ``` -------------------------------- ### Configure and Use ImageCache in Kingfisher Source: https://github.com/onevcat/kingfisher/blob/master/docs/development.md Demonstrates how to instantiate a custom ImageCache, set memory and disk storage limits, and apply the cache to an image request. It also shows manual storage and retrieval operations. ```swift let cache = ImageCache(name: "custom") cache.memoryStorage.config.totalCostLimit = 50 * 1024 * 1024 // 50MB cache.diskStorage.config.sizeLimit = 200 * 1024 * 1024 // 200MB // Use with options imageView.kf.setImage(with: url, options: [.targetCache(cache)]) // Manual cache operations cache.store(image, forKey: key) cache.retrieveImage(forKey: key) { result in // Handle cached image } ``` -------------------------------- ### Chaining Multiple ImageProcessors Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/CommonTasks/CommonTasks_Processor.md Shows how to combine multiple ImageProcessors sequentially using the '|>' operator. This allows for applying a series of transformations, such as blurring an image and then rounding its corners. ```swift // First blur the image, then make it round cornered. let processor = BlurImageProcessor(blurRadius: 4) |> RoundCornerImageProcessor(cornerRadius: 20) imageView.kf.setImage(with: url, options: [.processor(processor)]) ``` -------------------------------- ### Configure Cache Loading Options Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/CommonTasks/CommonTasks_Cache.md Demonstrates how to force a refresh by bypassing the cache or enabling offline mode to only retrieve images from the cache. ```swift // Force refresh imageView.kf.setImage(with: url, options: [.forceRefresh]) // Only from cache imageView.kf.setImage(with: url, options: [.onlyFromCache]) ``` -------------------------------- ### Image Prefetching Source: https://context7.com/onevcat/kingfisher/llms.txt Demonstrates how to use ImagePrefetcher to download and cache images in the background before they are needed, optimizing performance for collection and table views. ```APIDOC ## Image Prefetching `ImagePrefetcher` downloads and caches images in the background before they're needed. This is especially useful with table views and collection views to prefetch upcoming cells' images. ### Basic Prefetching ```swift import Kingfisher let urls = [ URL(string: "https://example.com/image1.png")!, URL(string: "https://example.com/image2.png")!, URL(string: "https://example.com/image3.png")! ] let prefetcher = ImagePrefetcher(urls: urls) { skipped, failed, completed in print("Prefetch completed") print("Skipped (already cached): \(skipped.count)") print("Failed: \(failed.count)") print("Completed: \(completed.count)") } prefetcher.start() ``` ### Prefetching with Progress Tracking ```swift import Kingfisher let prefetcher = ImagePrefetcher( urls: urls, options: [.cacheOriginalImage], progressBlock: { skipped, failed, completed in let total = skipped.count + failed.count + completed.count print("Progress: \(total)/\(urls.count)") }, completionHandler: { skipped, failed, completed in print("All done!") } ) prefetcher.maxConcurrentDownloads = 3 prefetcher.start() ``` ### Stopping Prefetching ```swift prefetcher.stop() ``` ### Using with UICollectionView Prefetching ```swift import Kingfisher class ViewController: UIViewController, UICollectionViewDataSourcePrefetching { var imageURLs: [URL] = [] func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { let urls = indexPaths.compactMap { imageURLs[$0.row] } ImagePrefetcher(urls: urls).start() } func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) { // Optionally cancel prefetching } } ``` ``` -------------------------------- ### Implement Low Data Mode support Source: https://context7.com/onevcat/kingfisher/llms.txt Shows how to provide alternative low-resolution image sources to optimize performance when the system detects Low Data Mode. ```swift import Kingfisher let highResURL = URL(string: "https://example.com/image-high.png")! let lowResURL = URL(string: "https://example.com/image-low.png")! // UIKit imageView.kf.setImage(with: highResURL, options: [.lowDataMode(.network(lowResURL))]) // SwiftUI KFImage.url(highResURL) .lowDataModeSource(.network(lowResURL)) .resizable() ``` -------------------------------- ### Using Placeholders Source: https://github.com/onevcat/kingfisher/wiki/Cheat-Sheet Displays a placeholder image or custom view while the primary image is being downloaded. The placeholder is removed once the download completes. ```swift let image = UIImage(named: "default_profile_icon") imageView.kf.setImage(with: url, placeholder: image) ``` -------------------------------- ### Display Placeholder Image or View Source: https://github.com/onevcat/kingfisher/blob/master/Sources/Documentation.docc/CommonTasks/CommonTasks.md Sets a placeholder image or a custom view that conforms to the Placeholder protocol while the target image is downloading. ```swift let image = UIImage(named: "default_profile_icon") imageView.kf.setImage(with: url, placeholder: image) // Custom view placeholder class MyView: UIView {} extension MyView: Placeholder {} imageView.kf.setImage(with: url, placeholder: MyView()) ``` -------------------------------- ### KFOptionSetter Protocol for Fluent Configuration (Swift) Source: https://github.com/onevcat/kingfisher/blob/master/docs/development.md Implements a protocol-based fluent API for configuring Kingfisher options. It allows setting properties like target cache and downloader through chained method calls, enhancing readability and ease of use. ```swift @MainActor public protocol KFOptionSetter { var options: KingfisherParsedOptionsInfo { get nonmutating set } var onFailureDelegate: Delegate { get } var onSuccessDelegate: Delegate { get } var onProgressDelegate: Delegate<(Int64, Int64), Void> { get } } extension KFOptionSetter { public func targetCache(_ cache: ImageCache) -> Self { options.targetCache = cache return self } public func downloader(_ downloader: ImageDownloader) -> Self { options.downloader = downloader return self } } ```