The Kingfisher recommended in this issue is a powerful pure Swift library used for downloading and caching images from the web.
Kingfisher gives you the opportunity to use pure Swift to process remote images in your next application.
Kingfisher features
- Asynchronous image download and caching.
- Load images from URLSession based on network or locally provided data.
- Provide useful image processors and filters.
- Multi layer hybrid cache of memory and disk.
- Fine control over caching behavior. Customizable expiration dates and size restrictions.
- Can cancel downloads and automatically reuse previously downloaded content to improve performance.
- Independent components. Use downloaders, caching systems, and image processors as needed.
- Pre fetch images and display them from cache to enhance your application.
- UIImageView, NSImageView, NSButton, UIButton, NSTextAttachment,The extension WKInterface Image is used to directly set images from URLs.TVMonogramViewCPListItem
- Built in transition animation when setting up images.
- Customizable placeholders and indicators when loading images.
- Easy to expand image processing and image formats.
- Low data mode support.
- SwiftUI support.
Kingfisher
import Kingfisher
let url = URL(string: "https://example.com/image.png")
imageView.kf.setImage(with: url)
Kingfisher will download the image URL, send it to the memory cache and disk cache, and use imageView When you set it up with the same URL later, the image will be retrieved from the cache and displayed immediately.
If you use SwiftUI, it can also work:
var body: some View {
KFImage(URL(string: "https://example.com/image.png")!)
}
A more advanced example
With powerful options, you can complete challenging tasks in a simple way with Kingfisher. For example, the following code:
- Download high-resolution images.
- Downsample it to match the size of the image view.
- Make it rotate at a given radius.
- Display system indicators and placeholder images during download.
- After preparation, it will animate the small thumbnail image with a “fade in” effect.
- The original large image is also cached to disk for future use to avoid downloading it again in the detailed view.
- When the task is completed, the console log will be printed, whether it is successful or failed.
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)")
}
}
method chaining
If you are not a fan of KF extensions, you may also prefer to use KF builders and link method calls. The following code does the same thing:
// 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
// Progress updated
},
completionHandler: { result in
// Done
}
)
// 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)
Even better, if you want to switch to SwiftUI in the future, just change the content on KF to KFImage, and you’ll be done:
struct ContentView: View {
var body: some View {
KFImage.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 }
}
}
require
- iOS 12.0+ / macOS 10.14+ / tvOS 12.0+ / watchOS 5.0+(If you only use UIKit/AppKit)
- iOS 14.0+ / macOS 11.0+ / tvOS 14.0+ / watchOS 7.0+(If you use it in SwiftUI)
- Swift 5.0+
installation guide
Swift Package Manager
- Select File>Swift Package>Add Package Dependency. https://github.com/onevcat/Kingfisher.git Enter in the ‘Select Package Repository’ dialog box.
- On the next page, specify the version parsing rule as’ Up to Next Major ‘, with the earliest version being’ 7.0.0 ‘.
- After checking the source code and parsing the version in Xcode, you can select the “Kingfisher” library and add it to your application target.
Cocoa
CocoaPods is the dependency manager for the Cocoa project. You can install it using the following command:
$ gem install cocoapods
To integrate Kingfisher into your Xcode project using CocoaPods, specify it as your Podfile:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '12.0'
use_frameworks!
target 'MyApp' do
# your other pod
# ...
pod 'Kingfisher', '~> 7.0'
end
Then, run the following command:
$ pod install
After installing any content from CocoaPods, you should open {Project}. xcworkspace instead of opening it. {Project}.xcodeproj
Carthage
Carthage is a decentralized dependency manager for Cocoa applications. To install the Carthage tool, you can use Homebrew.
$ brew update
$ brew install carthage
To integrate Kingfisher into your Xcode project using Carthage, please go to your Cartfile:
github "onevcat/Kingfisher" ~> 7.0
Then, run the following command to build the Kingfisher framework:
$ carthage update Kingfisher --platform iOS
# Or `--platform macOS`, `--platform tvOS`, `--platform watchOS`
Finally, you need to manually set up your Xcode project to add the Kingfisher framework:
- On the “General” settings tab of the application target, in the “Linking Frameworks and Libraries” section, drag and drop each framework you want to use from the Carthage/Build folder on the disk.
- On the “Build Phases” settings tab of the application target, click the “+” icon and select “New Run Script Phase”. Create a running script that includes the following content:
/usr/local/bin/carthage copy-frameworks
- Add the path of the framework to be used under ‘Input Files’:
$(SRCROOT)/Carthage/Build/iOS/Kingfisher.framework
- Add the path of the copied framework to the ‘Output File’:
$(BUILT_PRODUCTS_DIR)/$(FRAMEWORKS_FOLDER_PATH)/Kingfisher.framework
—END—
Open source protocol:MIT license