Swiftpack.co - Package - onevcat/Kingfisher

Kingfisher


Kingfisher is a powerful, pure-Swift library for downloading and caching images from the web. It provides you a chance to use a pure-Swift way to work with remote images in your next app.

Features

  • ☑ Asynchronous image downloading and caching.
  • ☑ Loading image from either URLSession-based networking or local provided data.
  • ☑ Useful image processors and filters provided.
  • ☑ Multiple-layer hybrid cache for both memory and disk.
  • ☑ Fine control on cache behavior. Customizable expiration date and size limit.
  • ☑ Cancelable downloading and auto-reusing previous downloaded content to improve performance.
  • ☑ Independent components. Use the downloader, caching system and image processors separately as you need.
  • ☑ Prefetching images and showing them from cache to boost your app.
  • ☑ View extensions for UIImageView, NSImageView, NSButton and UIButton to directly set an image from a URL.
  • ☑ Built-in transition animation when setting images.
  • ☑ Customizable placeholder and indicator while loading images.
  • ☑ Extensible image processing and image format easily.
  • ☑ SwiftUI support.

Kingfisher 101

The simplest use-case is setting an image to an image view with the UIImageView extension:

let url = URL(string: "https://example.com/image.png")
imageView.kf.setImage(with: url)

Kingfisher will download the image from url, send it to both memory cache and disk cache, and display it in imageView. When you set with the same URL later, the image will be retrieved from cache and shown immediately.

It also works if you use SwiftUI:

import KingfisherSwiftUI

var body: some View {
    KFImage(URL(string: "https://example.com/image.png")!)
}

A More Advanced Example

With the powerful options, you can do hard tasks with Kingfisher in a simple way. For example, the code below:

  1. Downloads a high-resolution image.
  2. Downsamples it to match the image view size.
  3. Makes it round cornered with a given radius.
  4. Shows a system indicator and a placeholder image while downloading.
  5. When prepared, it animates the small thumbnail image with a "fade in" effect.
  6. The original large image is also cached to disk for later use, to get rid of downloading it again in a detail view.
  7. A console log is printed when the task finishes, either for success or failure.
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)")
    }
}

It is really a very common situation I can meet in my daily work. Think about how many lines you need to write without Kingfisher. You will fall in love with it if you give it a try!

Learn More

To learn the using of Kingfisher by more examples, take a look at the Cheat Sheet. There we summarized most common tasks in Kingfisher, you can get a better idea on what this framework can do. There are also some tips for performance in the same page, remember to check them too.

Requirements

  • iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+
  • Swift 4.0+

Kingfisher 5.0 Migration - Kingfisher 5.x is NOT fully compatible with version 4.x. However, the migration is not difficult. Depending on your use cases, it may take no effect or several minutes to modify your existing code for the new version. Please follow the migration guide when you prepare to upgrade Kingfisher in your project.

If you are using an even earlier version, see the guides below to know the steps for migrating.

  • Kingfisher 4.0 Migration - Kingfisher 3.x should be source compatible to Kingfisher 4. The reason for a major update is that we need to specify the Swift version explicitly for Xcode. All deprecated methods in Kingfisher 3 has been removed, so please ensure you have no warning left before you migrate from Kingfisher 3 to Kingfisher 4. If you have any trouble in migrating, please open an issue to discuss.
  • Kingfisher 3.0 Migration - If you are upgrading to Kingfisher 3.x from an earlier version, please read this for more information.

Next Steps

We prepared a wiki page. You can find tons of useful things there.

  • Installation Guide - Follow it to integrate Kingfisher into your project.
  • Cheat Sheet- Curious about what Kingfisher could do and how would it look like when used in your project? See this page for useful code snippets. If you are already familiar with Kingfisher, you could also learn new tricks to improve the way you use Kingfisher!
  • API Reference - Lastly, please remember to read the full whenever you may need a more detailed reference.

Other

Future of Kingfisher

I want to keep Kingfisher lightweight. This framework will focus on providing a simple solution for downloading and caching images. This doesn’t mean the framework can’t be improved. Kingfisher is far from perfect, so necessary and useful updates will be made to make it better.

Developments and Tests

Any contributing and pull requests are warmly welcome. However, before you plan to implement some features or try to fix an uncertain issue, it is recommended to open a discussion first. It would be appreciated if your pull requests could build and with all tests green. :)

About the logo

The logo of Kingfisher is inspired by Tangram (七巧板), a dissection puzzle consisting of seven flat shapes from China. I believe she's a kingfisher bird instead of a swift, but someone insists that she is a pigeon. I guess I should give her a name. Hi, guys, do you have any suggestions?

Contact

Follow and contact me on Twitter or Sina Weibo. If you find an issue, just open a ticket. Pull requests are warmly welcome as well.

Contributors

This project exists thanks to all the people who contribute. [Contribute].

Backers

Thank you to all our backers! Your support is really important for the project and encourages us to continue. 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

Kingfisher is released under the MIT license. See LICENSE for details.

Github

link
Stars: 16196

Dependencies

Releases

5.14.0 - Retry Strategy - 2020-05-12 15:11:16

Add

  • A .retryStrategy option and associated RetryStrategy to define a highly customizable retry mechanism in Kingfisher. [#1424]
  • Built-in DelayRetryStrategy to provide a most common used retry strategy implementation. It simplifies the normal retry requirement when downloading an image from network. #1447
  • Now you can set the round corner radius for a RoundCornerImageProcessor in a fraction way. This is useful when you do not know the desire image view size, but still want to clip any received image to a certain round corner ratio (such as a circle for any image). #1443
  • Add an isLoaded binding to KFImage to follow SwiftUI pattern better. #1429

Fix

  • An issue that .imageModifier option not working on an ImageProvider provided image. #1435
  • A workaround for making xcframework continue to work when exported with Swift 5.2 compiler and Xcode 11.4. #1444

5.13.4 - Build Configurations - 2020-04-11 01:28:53

Fix

  • Expose all build configurations in Package.swift file for Swift Package Manager. Now you can choose the linking style by yourself. #1426

5.13.3 - Dynamic SPM - 2020-04-01 02:57:21

Fix

  • Allows Carthage to build this library for macOS. #1413
  • Explicitly specify to build as a dynamic framework for Swift Package Manager. #1420

5.13.2 - KFImage Orientation - 2020-02-27 15:51:00

Fix

  • An issue for KFImage when resizing images with different EXIF orientation other than top. #1396
  • A race condition when setting CacheCallbackCoordinator state. #1394
  • Move an @objc attribute to prevent warnings in Xcode 11.4.

5.13.1 - Internal Warning - 2020-02-17 13:13:01

Fix

  • Fix an unused variable warning which is on by default in Xcode 11.4 and Swift 5.2, which makes CocoaPods angry when compiling. #1393

5.13.0 - New Year 2020 - 2020-01-17 14:28:52

Add

  • Mark DefaultCacheSerializer as public and enables the ability of original data caching. #1373
  • Add image compression quality parameter to DefaultCacheSerializer. #1372
  • A new contentURL property in ImageDataProvider to provide a URL when it makes sense. #1386

Fix

  • Now, local file URLs can be loaded as Resources without converted to LocalFileImageDataProvider explicitly. #1386

5.12.0 - White Overflow - 2019-12-13 14:32:29

Add

  • Two error cases under KingfisherError.CacheErrorReason to give out the detail error information and reason when a failure happens when caching the file on disk. Check .cannotCreateCacheFile and .cannotSetCacheFileAttribute if you need to handle these errors. #1365

Fix

  • A 32-bit Int overflow when calculating expiration duration when a large days value is set for StorageExpiration. #1371
  • The build config for SwiftUI sub-pod now only applies to the KingfisherSwiftUI scheme. #1368

5.11.0 - macCatalyst - 2019-11-30 02:23:31

Add

  • Support macCatalyst platform when building with Carthage. #1356

Fix

  • Fix an issue that image orientation not correctly applied when an image processor used. #1358

5.10.1 - Repeat Count - 2019-11-19 15:20:20

Fix

  • Fix a wrong calculation of repeatCount of AnimatedImageView. Now it can play correct count for an animated image. #1350
  • Make sure to skip disk cache when fromMemoryCacheOrRefresh set. #1351
  • Fix a issue which prevents building with Xcode 10. #1353

5.10.0 - Rex Rabbit - 2019-11-16 15:49:22

Add

  • An .alternativeSources option to provide a list of alternative image loading Sources. These Sources act as a fallback when the original Source downloading fails where Kingfisher will try to load images from. #1343

Fix

  • The .waitForCache option now also waits for caching for original image if the .cacheOriginalImage is also set. #1344
  • Now the retrieveImage methods in ImageCache calls its callbackQueue is .mainCurrentOrAsync by default instead of .untouch. It aligns the behavior of other parts in the framework. #1338
  • An issue that causes customize indicator not being placed with correct size. #1345
  • Performance improvement for loading progressive images. #1332

5.9.0 - Combination - 2019-10-24 11:34:41

Add

  • Introduce a |> operator for combining image processors. #1320

Fix

  • Improve performance of reading task identifier when handling downloading side effect. #1310
  • Improve some type conversion to boost building. #1321

5.8.3 - Carthage Cache - 2019-10-09 12:28:12

Fix

  • Generate Objective-C header to make carthage cache work again. #1308

5.8.2 - Game of Thrones - 2019-10-04 13:42:37

Fix

  • Fix broken semantic versioning introduced by 5.8.0. #1304
  • Remove implicit animations in SwiftUI when a .fade animation applied in the option. Now Kingfisher respect all animations set by users instead of overwriting it internally. #1301
  • Now project uses KingfisherSwiftUI with Swift Package Manager can be archived correctly. #1300

5.8.1 - Borderless - 2019-09-26 15:45:03

Fix

  • Remove the unexpected border in KFImage while loading the image. #1293

5.8.0 - Xcode 11 & SwiftUI - 2019-09-25 14:20:55

Add

  • Add support for Swift Package Manager. Now you can build and use Kingfisher with SPM under Xcode 11 and use it in all targets.
  • Add support for iPad Apps for Mac. You can use Kingfisher's UIKit extensions (like UIImage and UIImageView) on a catalyst project.
  • Add support for SwiftUI. Build and import KingfisherSwiftUI.framework or contain the "Kingfisher/SwiftUI" subpod, then you can use KFImage to load image asynchronously. KFImage provides a similar interface as View.Image.
  • Add support for building as a binary framework. A zipped file containing xcframework and related dSYMs is provided in the release page.
  • A diskCacheAccessExtendingExpiration option to give more control of disk cache extending behavior. #1287
  • Combine all targets into one. Now Kingfisher is a cross-platform target and you need to specify an SDK to build it.

Fix

  • Rename too generic typealias names in Kingfisher, to avoid conflicting with SwiftUI types. Original Kingfisher.Image is now Kingfisher.KFCrossPlatformImage. The similar rules are applied to other cross-platform typealias too, such as Kingfisher.View, Kingfisher.Color and more.
  • A potential thread issue in taskIdentifier which might cause a crash when using data provider. #1276
  • An issue that causes memory shortage when a large number of network images are loaded in a short time. #1270

5.7.1 - Thread Things - 2019-08-11 02:05:53

Fix

  • Setting runLoopMode for AnimatedImageView will trigger animation restart normally. #1253
  • A possible thread issue when removing storage object from memory cache by the cache policy. #1255
  • Manipulating on AnimateImageView's frame array is now thread safe. #1257

5.7.0 - Summer Bird - 2019-07-03 13:47:15

Add

  • Mark cacheFileURL(forKey:) of DiskStorage to public. #1214
  • Mark KingfisherManager initializer to public so other dependencies can customize the manager behavior. #1216

Fix

  • Performance improvement on progressive JPEG scanning. #1218
  • Fix a potential thread issue when checking progressive JPEG. #1220

Remove

  • The deprecated Result extensions for Swift 4 back compatibility are removed. #1224

5.6.0 - The Sands of Time - 2019-06-10 15:27:10

Add

  • Support extending memory cache TTL to a specified time instead of the fixed original expire setting. Use the .memoryCacheAccessExtendingExpiration to set a customize expiration extending duration when accessing the image. #1196
  • Add prebuilt binary framework when releasing to GitHub. Further supporting of fully compatible binary framework would come after Swift module stability. #1194

Fix

  • Resizing performance for animated images should be improved dramatically. #1189
  • A small optimization on MD5 calculation for image file cache key. #1183

5.5.0 - Progressive JPEG - 2019-05-16 15:10:51

Add

  • Add support for loading progressive JPEG images. This feature is still in beta and will be improved in the next few releases. To try it out, make sure you are loading a progressive JPEG image with a .progressiveJPEG options passed in. Thanks @lixiang1994 #1181
  • Choose to use Swift.Result as the default result type when Swift 5.0 or above is applied. #1146

Fix

  • Apply to some modern Swift syntax, which may also improve internal performance a bit. #1181

5.4.0 - Accio Support - 2019-04-24 13:56:28

Add

  • Add support for building project with Accio (and Swift Package Manager). #1153

Fix

  • Now maxCachePeriodInSecond of cache would treat 0 as expiring correctly. #1160
  • Normalization of image now returns an image with .up as orientation. #1163

5.3.1 - Prefetching Thread - 2019-03-28 14:34:03

Fix

  • Some thread issues which may cause crash when loading images by ImagePrefetcher. #1150
  • Setting a negative value by the deprecated maxCachePeriodInSecond API now expires the cache correctly. #1145

5.3.0 - Prefetching Sources - 2019-03-24 13:33:45

Add

  • Now ImagePretcher also supports using Source as fetching target. #1142
  • An option to skip file name hashing when storing image to disk cashe. #1140
  • Supports multiple Swift versions for CocoaPods 1.7.0.

Fix

  • An issue that loading a downsampled image from original version might lead to different scale and potential memory performance problem. #1126
  • Marking setter of kf wrapper as nonmutating and seperate value/reference version of KingfisherCompatible. This allows mutating properties on kf even with a let declaration. #1134
  • A regression which causes stack overflow when using ImagePretcher to load huge ammount of images. #1143

5.2.0 - Swift 5.0 - 2019-02-27 13:13:44

Add

  • Compatible with Swift 5.0 and Xcode 10.2. Now Kingfisher builds against Swift 4.0, 4.2 and 5.0. #1098

Fix

  • A possible dead lock when using ImagePretcher heavily in another thread. #1122
  • Redesign Result type based on Swift Result in standard library. Deprecate value and error getter for Kingfisher.Result.

5.1.1 - Racing - 2019-02-11 13:49:34

Fix

  • Deprecate incorrect ImageCache initializer with path parameter. Now use the cacheDirectoryURL version for clearer implemetation. #1114
  • Fix a race condition when setting download delegate from multiple ImagePrefetchers. #1109
  • Now directoryURL of disk storage backend is marked as public correctly. #1108

5.1.0 - Redirecting & Racing - 2019-01-12 11:12:49

Add

  • Add a ImageDownloadRedirectHandler for intercepting HTTP request which redirects. #1072

Fix

  • Some thread racing when downloading and resetting images in the same image view. #1089

5.0.1 - Interweave - 2018-12-17 14:50:04

Fix

  • Retrieving images from cache now respect options callbackQueue setting. #1066
  • A crash when passing zero or negative size to DownsamplingImageProcessor. #1073

5.0.0 - Reborn - 2018-12-08 11:14:32

Although most APIs are compatible, Kingfisher 5 contains breaking changes.

To know what's new in Kingfisher 5, check this wiki page. Depending on your use cases of Kingfisher 4, it may take no effort or at most several minutes to fix errors and warnings after upgrading. The upgrading should be easy enough for most users. Follow the Kingfisher 5.0 Migration Guide to migrate to the new version.

Add

  • Add Result type to Kingfisher. Now all callbacks in Kingfisher are using Result instead of tuples. This is more future-friendly and provides a modern way to make error handling better.
  • Make KingfisherError much more elaborate and accurate. Instead of simply provides the error code, now KingfisherError contains error reason and necessary associated values. It will help to understand and track the errors easier.
  • Better cache management by separating memory cache and disk cache to their own storages. Now you can use MemoryStorage and DiskStorage as the ImageCache backend.
  • Image cache of memory storage would be purged automatically in a certain time interval. This reduce memory pressure for other parts of your app.
  • The ImageCache is rewritten from scratch, to get benefit from new created MemoryStorage and DiskStorage. At the same time, this hybrid cache abstract keeps most API compatibility from the earlier versions.
  • Now the ImageCache can receive only raw Data object and cache it as needed.
  • A KingfisherParsedOptionsInfo type to parse KingfisherOptionsInfoItems in related API. This improves reusability and performance when handling options in Kingfisher.
  • An option to specify whether an image should also prefetched to memory cache or not.
  • An option to make the disk file loading synchronously instead of in its own I/O queue.
  • Options to specify cache expiration for either memory cache or disk cache. This gives you a chance to control cache lifetime in a per-task grain size.
  • Add a default maximum size for memory cache. Now only at most 25% of your device memory will be used to kept images in memory. You can also change this value if needed.
  • An option to specify a processing queue for image processors. This gives your flexibility if you want to use main queue or if you want to dispatch the processing to a different queue.
  • A DownsamplingImageProcessor for downsampling an image to a given size before loading it to memory.
  • Add ImageDataProvider protocol to make it possible to provide image data locally instead of downloading from network. Several concrete types are provided to load images from data format. Use LocalFileImageDataProvider to load an image from a local disk path, Base64ImageDataProvider to load image from a Base64 string representation and RawImageDataProvider to provide a raw Data object.
  • A general Source protocol to define from where the image should be loaded. Currently, we support to load an image from ImageDataProvider or from network now.

Fix

  • Now CommonCrypto from system is used to calculate file name from cache key, instead of using a customized hash algorithm.
  • An issue which causes ImageDownloader crashing when a lot of downloading tasks running at the same time.
  • All operations like image pretching and data receiving should now be performed in non-UI threads correctly.
  • Now KingfisherCompatible uses struct for kf namespacing for better performance.

4.10.1 - Time Machine - 2018-11-03 14:46:40

Fix

  • Add Swift 4 compatibility back.
  • Increase watchOS target to 3.0 in podspec.

4.10.0 - Swift 4.2 - 2018-09-19 15:36:56

Add

  • Support for building with Xcode 10 and Swift 4.2. This version requires Xcode 10 or later with Swift 4.2 compiler.

Fix

  • Improve performance when an invalide HTTP status code received. #985

4.9.0 - Patience is a Virtue - 2018-09-03 15:37:02

Add

  • Add a waitForCache option to allowing cache callback called after cache operation finishes. #963

Fix

  • Animated image now will recognize .once and .finite(1) the same thing. #982
  • Replace class-only protocol keyword with AnyObject as Swift convention. #983
  • A wrong cache callback parameter when storing cache with background decoding. #986
  • Access downloadHolder in a serial queue to avoid racing. #984