Kingfisher Documentation

Class Image​Cache

open class ImageCache  

Represents a hybrid caching system which is composed by a MemoryStorage.Backend and a DiskStorage.Backend. ImageCache is a high level abstract for storing an image as well as its data to disk memory and disk, and retrieving them back.

While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create your own cache object and configure its storages as your need. This class also provide an interface for you to set the memory and disk storage config.

Nested Type Aliases

Disk​Cache​Path​Closure

public typealias DiskCachePathClosure = (URL, String) -> URL

Closure that defines the disk cache path from a given path and cacheName.

Initializers

init(memory​Storage:​disk​Storage:​)

public init(
        memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>,
        diskStorage: DiskStorage.Backend<Data>) 

Creates an ImageCache from a customized MemoryStorage and DiskStorage.

Parameters

memory​Storage Memory​Storage.​Backend<KFCross​Platform​Image>

The MemoryStorage.Backend object to use in the image cache.

disk​Storage Disk​Storage.​Backend<Data>

The DiskStorage.Backend object to use in the image cache.

init(name:​)

public convenience init(name: String)  

Creates an ImageCache with a given name. Both MemoryStorage and DiskStorage will be created with a default config based on the name.

Parameters

name String

The name of cache object. It is used to setup disk cache directories and IO queue. You should not use the same name for different caches, otherwise, the disk storage would be conflicting to each other. The name should not be an empty string.

init(name:​cache​Directory​URL:​disk​Cache​Path​Closure:​)

public convenience init(
        name: String,
        cacheDirectoryURL: URL?,
        diskCachePathClosure: DiskCachePathClosure? = nil
    ) throws

Creates an ImageCache with a given name, cache directory path and a closure to modify the cache directory.

Parameters

name String

The name of cache object. It is used to setup disk cache directories and IO queue. You should not use the same name for different caches, otherwise, the disk storage would be conflicting to each other.

cache​Directory​URL URL?

Location of cache directory URL on disk. It will be internally pass to the initializer of DiskStorage as the disk cache directory. If nil, the cache directory under user domain mask will be used.

disk​Cache​Path​Closure Disk​Cache​Path​Closure?

Closure that takes in an optional initial path string and generates the final disk cache path. You could use it to fully customize your cache path.

Throws

An error that happens during image cache creating, such as unable to create a directory at the given path.

Properties

`default`

public static let `default`  

The default ImageCache object. Kingfisher will use this cache for its related methods if there is no other cache specified. The name of this default cache is "default", and you should not use this name for any of your customize cache.

memory​Storage

public let memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>

The MemoryStorage.Backend object used in this cache. This storage holds loaded images in memory with a reasonable expire duration and a maximum memory usage. To modify the configuration of a storage, just set the storage config and its properties.

disk​Storage

public let diskStorage: DiskStorage.Backend<Data>

The DiskStorage.Backend object used in this cache. This storage stores loaded images in disk with a reasonable expire duration and a maximum disk usage. To modify the configuration of a storage, just set the storage config and its properties.

Methods

store(_:​original:​for​Key:​options:​to​Disk:​completion​Handler:​)

open func store(_ image: KFCrossPlatformImage,
                    original: Data? = nil,
                    forKey key: String,
                    options: KingfisherParsedOptionsInfo,
                    toDisk: Bool = true,
                    completionHandler: ((CacheStoreResult) -> Void)? = nil) 

store(_:​original:​for​Key:​processor​Identifier:​cache​Serializer:​to​Disk:​callback​Queue:​completion​Handler:​)

open func store(_ image: KFCrossPlatformImage,
                      original: Data? = nil,
                      forKey key: String,
                      processorIdentifier identifier: String = "",
                      cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
                      toDisk: Bool = true,
                      callbackQueue: CallbackQueue = .untouch,
                      completionHandler: ((CacheStoreResult) -> Void)? = nil) 

Stores an image to the cache.

Parameters

image KFCross​Platform​Image

The image to be stored.

original Data?

The original data of the image. This value will be forwarded to the provided serializer for further use. By default, Kingfisher uses a DefaultCacheSerializer to serialize the image to data for caching in disk, it checks the image format based on original data to determine in which image format should be used. For other types of serializer, it depends on their implementation detail on how to use this original data.

key String

The key used for caching the image.

identifier String

The identifier of processor being used for caching. If you are using a processor for the image, pass the identifier of processor to this parameter.

serializer Cache​Serializer

The CacheSerializer

to​Disk Bool

Whether this image should be cached to disk or not. If false, the image is only cached in memory. Otherwise, it is cached in both memory storage and disk storage. Default is true.

callback​Queue Callback​Queue

The callback queue on which completionHandler is invoked. Default is .untouch. For case that toDisk is false, a .untouch queue means callbackQueue will be invoked from the caller queue of this method. If toDisk is true, the completionHandler will be called from an internal file IO queue. To change this behavior, specify another CallbackQueue value.

completion​Handler ((Cache​Store​Result) -> Void)?

A closure which is invoked when the cache operation finishes.

store​ToDisk(_:​for​Key:​processor​Identifier:​expiration:​callback​Queue:​completion​Handler:​)

open func storeToDisk(
        _ data: Data,
        forKey key: String,
        processorIdentifier identifier: String = "",
        expiration: StorageExpiration? = nil,
        callbackQueue: CallbackQueue = .untouch,
        completionHandler: ((CacheStoreResult) -> Void)? = nil) 

remove​Image(for​Key:​processor​Identifier:​from​Memory:​from​Disk:​callback​Queue:​completion​Handler:​)

open func removeImage(forKey key: String,
                          processorIdentifier identifier: String = "",
                          fromMemory: Bool = true,
                          fromDisk: Bool = true,
                          callbackQueue: CallbackQueue = .untouch,
                          completionHandler: (() -> Void)? = nil) 

Removes the image for the given key from the cache.

Parameters

key String

The key used for caching the image.

identifier String

The identifier of processor being used for caching. If you are using a processor for the image, pass the identifier of processor to this parameter.

from​Memory Bool

Whether this image should be removed from memory storage or not. If false, the image won't be removed from the memory storage. Default is true.

from​Disk Bool

Whether this image should be removed from disk storage or not. If false, the image won't be removed from the disk storage. Default is true.

callback​Queue Callback​Queue

The callback queue on which completionHandler is invoked. Default is .untouch.

completion​Handler (() -> Void)?

A closure which is invoked when the cache removing operation finishes.

retrieve​Image(for​Key:​options:​callback​Queue:​completion​Handler:​)

open func retrieveImage(
        forKey key: String,
        options: KingfisherParsedOptionsInfo,
        callbackQueue: CallbackQueue = .mainCurrentOrAsync,
        completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?) 

Gets an image for a given key from the cache, either from memory storage or disk storage.

Parameters

key String

The key used for caching the image.

options Kingfisher​Parsed​Options​Info

The KingfisherParsedOptionsInfo options setting used for retrieving the image.

callback​Queue Callback​Queue

The callback queue on which completionHandler is invoked. Default is .mainCurrentOrAsync.

completion​Handler ((Result<Image​Cache​Result, Kingfisher​Error>) -> Void)?

A closure which is invoked when the image getting operation finishes. If the image retrieving operation finishes without problem, an ImageCacheResult value will be sent to this closure as result. Otherwise, a KingfisherError result with detail failing reason will be sent.

retrieve​Image(for​Key:​options:​callback​Queue:​completion​Handler:​)

open func retrieveImage(forKey key: String,
                               options: KingfisherOptionsInfo? = nil,
                        callbackQueue: CallbackQueue = .mainCurrentOrAsync,
                     completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?) 

Gets an image for a given key from the cache, either from memory storage or disk storage.

Note: This method is marked as open for only compatible purpose. Do not overide this method. Instead, override the version receives KingfisherParsedOptionsInfo instead.

Parameters

key String

The key used for caching the image.

options Kingfisher​Options​Info?

The KingfisherOptionsInfo options setting used for retrieving the image.

callback​Queue Callback​Queue

The callback queue on which completionHandler is invoked. Default is .mainCurrentOrAsync.

completion​Handler ((Result<Image​Cache​Result, Kingfisher​Error>) -> Void)?

A closure which is invoked when the image getting operation finishes. If the image retrieving operation finishes without problem, an ImageCacheResult value will be sent to this closure as result. Otherwise, a KingfisherError result with detail failing reason will be sent.

retrieve​Image​InMemory​Cache(for​Key:​options:​)

open func retrieveImageInMemoryCache(
        forKey key: String,
        options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? 

Gets an image for a given key from the memory storage.

Parameters

key String

The key used for caching the image.

options Kingfisher​Parsed​Options​Info

The KingfisherParsedOptionsInfo options setting used for retrieving the image.

Returns

The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or has already expired, nil is returned.

retrieve​Image​InMemory​Cache(for​Key:​options:​)

open func retrieveImageInMemoryCache(
        forKey key: String,
        options: KingfisherOptionsInfo? = nil) -> KFCrossPlatformImage? 

Gets an image for a given key from the memory storage.

Note: This method is marked as open for only compatible purpose. Do not overide this method. Instead, override the version receives KingfisherParsedOptionsInfo instead.

Parameters

key String

The key used for caching the image.

options Kingfisher​Options​Info?

The KingfisherOptionsInfo options setting used for retrieving the image.

Returns

The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or has already expired, nil is returned.

retrieve​Image​InDisk​Cache(for​Key:​options:​callback​Queue:​completion​Handler:​)

open func retrieveImageInDiskCache(
        forKey key: String,
        options: KingfisherOptionsInfo? = nil,
        callbackQueue: CallbackQueue = .untouch,
        completionHandler: @escaping (Result<KFCrossPlatformImage?, KingfisherError>) -> Void) 

Gets an image for a given key from the disk storage.

Parameters

key String

The key used for caching the image.

options Kingfisher​Options​Info?

The KingfisherOptionsInfo options setting used for retrieving the image.

callback​Queue Callback​Queue

The callback queue on which completionHandler is invoked. Default is .untouch.

completion​Handler @escaping (Result<KFCross​Platform​Image?, Kingfisher​Error>) -> Void

A closure which is invoked when the operation finishes.

clear​Cache(completion:​)

public func clearCache(completion handler: (() -> Void)? = nil)  

Clears the memory & disk storage of this cache. This is an async operation.

Parameters

handler (() -> Void)?

A closure which is invoked when the cache clearing operation finishes. This handler will be called from the main queue.

clear​Memory​Cache()

@objc public func clearMemoryCache()  

Clears the memory storage of this cache.

clear​Disk​Cache(completion:​)

open func clearDiskCache(completion handler: (() -> Void)? = nil)  

Clears the disk storage of this cache. This is an async operation.

Parameters

handler (() -> Void)?

A closure which is invoked when the cache clearing operation finishes. This handler will be called from the main queue.

clean​Expired​Cache(completion:​)

open func cleanExpiredCache(completion handler: (() -> Void)? = nil)  

Clears the expired images from memory & disk storage. This is an async operation.

clean​Expired​Memory​Cache()

open func cleanExpiredMemoryCache()  

Clears the expired images from disk storage.

clean​Expired​Disk​Cache(completion:​)

open func cleanExpiredDiskCache(completion handler: (() -> Void)? = nil)  

Clears the expired images from disk storage. This is an async operation.

Parameters

handler (() -> Void)?

A closure which is invoked when the cache clearing operation finishes. This handler will be called from the main queue.

background​Clean​Expired​Disk​Cache()

@objc public func backgroundCleanExpiredDiskCache()  

Clears the expired images from disk storage when app is in background. This is an async operation. In most cases, you should not call this method explicitly. It will be called automatically when UIApplicationDidEnterBackgroundNotification received.

image​Cached​Type(for​Key:​processor​Identifier:​)

open func imageCachedType(
        forKey key: String,
        processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> CacheType

Returns the cache type for a given key and identifier combination. This method is used for checking whether an image is cached in current cache. It also provides information on which kind of cache can it be found in the return value.

Parameters

key String

The key used for caching the image.

identifier String

Processor identifier which used for this image. Default is the identifier of DefaultImageProcessor.default.

Returns

A CacheType instance which indicates the cache status. .none means the image is not in cache or it is already expired.

is​Cached(for​Key:​processor​Identifier:​)

public func isCached(
        forKey key: String,
        processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> Bool

Returns whether the file exists in cache for a given key and identifier combination.

Parameters

key String

The key used for caching the image.

identifier String

Processor identifier which used for this image. Default is the identifier of DefaultImageProcessor.default.

Returns

A Bool which indicates whether a cache could match the given key and identifier combination.

hash(for​Key:​processor​Identifier:​)

open func hash(
        forKey key: String,
        processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String

Gets the hash used as cache file name for the key.

Parameters

key String

The key used for caching the image.

identifier String

Processor identifier which used for this image. Default is the identifier of DefaultImageProcessor.default.

Returns

The hash which is used as the cache file name.

calculate​Disk​Storage​Size(completion:​)

open func calculateDiskStorageSize(completion handler: @escaping ((Result<UInt, KingfisherError>) -> Void))  

Calculates the size taken by the disk storage. It is the total file size of all cached files in the diskStorage on disk in bytes.

Parameters

handler @escaping ((Result<UInt, Kingfisher​Error>) -> Void)

Called with the size calculating finishes. This closure is invoked from the main queue.

cache​Path(for​Key:​processor​Identifier:​)

open func cachePath(
        forKey key: String,
        processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String

Gets the cache path for the key. It is useful for projects with web view or anyone that needs access to the local file path.

i.e. Replacing the <img src='path_for_key'> tag in your HTML.

You could use isCached(forKey:) method to check whether the image is cached under that key in disk.

Parameters

key String

The key used for caching the image.

identifier String

Processor identifier which used for this image. Default is the identifier of DefaultImageProcessor.default.

Returns

The disk path of cached image under the given key and identifier.