ImageCache
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.
-
The default
ImageCache
object. Kingfisher will use this cache for its related methods if there is no other cache specified. Thename
of this default cache isdefault
, and you should not use this name for any of your customize cache.Declaration
Swift
public static let `default`: ImageCache
-
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 storageconfig
and its properties.Declaration
Swift
public let memoryStorage: MemoryStorage.Backend<Image>
-
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 storageconfig
and its properties.Declaration
Swift
public let diskStorage: DiskStorage.Backend<Data>
-
Closure that defines the disk cache path from a given path and cacheName.
Declaration
Swift
public typealias DiskCachePathClosure = (URL, String) -> URL
-
Creates an
ImageCache
from a customizedMemoryStorage
andDiskStorage
.Declaration
Swift
public init( memoryStorage: MemoryStorage.Backend<Image>, diskStorage: DiskStorage.Backend<Data>)
Parameters
memoryStorage
The
MemoryStorage.Backend
object to use in the image cache.diskStorage
The
DiskStorage.Backend
object to use in the image cache. -
Creates an
ImageCache
with a givenname
. BothMemoryStorage
andDiskStorage
will be created with a default config based on thename
.Declaration
Swift
public convenience init(name: String)
Parameters
name
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. Thename
should not be an empty string. -
Creates an
ImageCache
with a givenname
, cache directorypath
and a closure to modify the cache directory.Throws
An error that happens during image cache creating, such as unable to create a directory at the given path.Declaration
Swift
public convenience init( name: String, cacheDirectoryURL: URL?, diskCachePathClosure: DiskCachePathClosure? = nil) throws
Parameters
name
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.cacheDirectoryURL
Location of cache directory URL on disk. It will be internally pass to the initializer of
DiskStorage
as the disk cache directory. Ifnil
, the cache directory under user domain mask will be used.diskCachePathClosure
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.
-
Undocumented
Declaration
Swift
open func store(_ image: Image, original: Data? = nil, forKey key: String, options: KingfisherParsedOptionsInfo, toDisk: Bool = true, completionHandler: ((CacheStoreResult) -> Void)? = nil)
-
store(_:original:forKey:processorIdentifier:cacheSerializer:toDisk:callbackQueue:completionHandler:)
Stores an image to the cache.
Declaration
Swift
open func store(_ image: Image, original: Data? = nil, forKey key: String, processorIdentifier identifier: String = "", cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default, toDisk: Bool = true, callbackQueue: CallbackQueue = .untouch, completionHandler: ((CacheStoreResult) -> Void)? = nil)
Parameters
image
The image to be stored.
original
The original data of the image. This value will be forwarded to the provided
serializer
for further use. By default, Kingfisher uses aDefaultCacheSerializer
to serialize the image to data for caching in disk, it checks the image format based onoriginal
data to determine in which image format should be used. For other types ofserializer
, it depends on their implementation detail on how to use this original data.key
The key used for caching the image.
identifier
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
The
CacheSerializer
toDisk
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 istrue
.callbackQueue
The callback queue on which
completionHandler
is invoked. Default is.untouch
. For case thattoDisk
isfalse
, a.untouch
queue meanscallbackQueue
will be invoked from the caller queue of this method. IftoDisk
istrue
, thecompletionHandler
will be called from an internal file IO queue. To change this behavior, specify anotherCallbackQueue
value.completionHandler
A closure which is invoked when the cache operation finishes.
-
Undocumented
Declaration
Swift
open func storeToDisk( _ data: Data, forKey key: String, processorIdentifier identifier: String = "", expiration: StorageExpiration? = nil, callbackQueue: CallbackQueue = .untouch, completionHandler: ((CacheStoreResult) -> Void)? = nil)
-
Removes the image for the given key from the cache.
Declaration
Swift
open func removeImage(forKey key: String, processorIdentifier identifier: String = "", fromMemory: Bool = true, fromDisk: Bool = true, callbackQueue: CallbackQueue = .untouch, completionHandler: (() -> Void)? = nil)
Parameters
key
The key used for caching the image.
identifier
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.
fromMemory
Whether this image should be removed from memory storage or not. If
false
, the image won’t be removed from the memory storage. Default istrue
.fromDisk
Whether this image should be removed from disk storage or not. If
false
, the image won’t be removed from the disk storage. Default istrue
.callbackQueue
The callback queue on which
completionHandler
is invoked. Default is.untouch
.completionHandler
A closure which is invoked when the cache removing operation finishes.
-
Gets an image for a given key from the cache, either from memory storage or disk storage.
Declaration
Swift
open func retrieveImage(forKey key: String, options: KingfisherOptionsInfo? = nil, callbackQueue: CallbackQueue = .untouch, completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?)
Parameters
key
The key used for caching the image.
options
The
KingfisherOptionsInfo
options setting used for retrieving the image.callbackQueue
The callback queue on which
completionHandler
is invoked. Default is.untouch
.completionHandler
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, aKingfisherError
result with detail failing reason will be sent. -
Gets an image for a given key from the memory storage.
Declaration
Swift
open func retrieveImageInMemoryCache( forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image?
Parameters
key
The key used for caching the image.
options
The
KingfisherOptionsInfo
options setting used for retrieving the image.Return Value
The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or has already expired,
nil
is returned. -
Gets an image for a given key from the disk storage.
Declaration
Swift
open func retrieveImageInDiskCache( forKey key: String, options: KingfisherOptionsInfo? = nil, callbackQueue: CallbackQueue = .untouch, completionHandler: @escaping (Result<Image?, KingfisherError>) -> Void)
Parameters
key
The key used for caching the image.
options
The
KingfisherOptionsInfo
options setting used for retrieving the image.callbackQueue
The callback queue on which
completionHandler
is invoked. Default is.untouch
.completionHandler
A closure which is invoked when the operation finishes.
-
Clears the memory storage of this cache.
Declaration
Swift
@objc public func clearMemoryCache()
-
Clears the disk storage of this cache. This is an async operation.
Declaration
Swift
open func clearDiskCache(completion handler: (() -> ())? = nil)
Parameters
handler
A closure which is invoked when the cache clearing operation finishes. This
handler
will be called from the main queue. -
Clears the expired images from disk storage. This is an async operation.
Declaration
Swift
open func cleanExpiredMemoryCache()
-
Clears the expired images from disk storage. This is an async operation.
Declaration
Swift
open func cleanExpiredDiskCache(completion handler: (() -> Void)? = nil)
Parameters
handler
A closure which is invoked when the cache clearing operation finishes. This
handler
will be called from the main queue. -
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.Declaration
Swift
@objc public func backgroundCleanExpiredDiskCache()
-
Returns the cache type for a given
key
andidentifier
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.Declaration
Swift
open func imageCachedType( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> CacheType
Parameters
key
The key used for caching the image.
identifier
Processor identifier which used for this image. Default is the
identifier
ofDefaultImageProcessor.default
.Return Value
A
CacheType
instance which indicates the cache status..none
means the image is not in cache or it is already expired. -
Returns whether the file exists in cache for a given
key
andidentifier
combination.Note
The return value does not contain information about from which kind of storage the cache matches. To get the information about cache type according
CacheType
, useimageCachedType(forKey:processorIdentifier:)
instead.Declaration
Swift
public func isCached( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> Bool
Parameters
key
The key used for caching the image.
identifier
Processor identifier which used for this image. Default is the
identifier
ofDefaultImageProcessor.default
.Return Value
A
Bool
which indicates whether a cache could match the givenkey
andidentifier
combination. -
Gets the hash used as cache file name for the key.
Note
By default, for a given combination of
key
andidentifier
,ImageCache
will use the value returned by this method as the cache file name. You can use this value to check and match cache file if you need.Declaration
Swift
open func hash( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
Parameters
key
The key used for caching the image.
identifier
Processor identifier which used for this image. Default is the
identifier
ofDefaultImageProcessor.default
.Return Value
The hash which is used as the cache file name.
-
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.Declaration
Swift
open func calculateDiskStorageSize(completion handler: @escaping ((Result<UInt, KingfisherError>) -> Void))
Parameters
handler
Called with the size calculating finishes. This closure is invoked from the main queue.
-
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.Note
This method does not guarantee there is an image already cached in the returned path. It just gives your the path that the image should be, if it exists in disk storage.
You could use
isCached(forKey:)
method to check whether the image is cached under that key in disk.Declaration
Swift
open func cachePath( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
Parameters
key
The key used for caching the image.
identifier
Processor identifier which used for this image. Default is the
identifier
ofDefaultImageProcessor.default
.Return Value
The disk path of cached image under the given
key
andidentifier
.
-
Creates an
ImageCache
with a givenname
, cache directorypath
and a closure to modify the cache directory.Throws
An error that happens during image cache creating, such as unable to create a directory at the given path.Declaration
Swift
@available(*, deprecated, renamed: "init(name:cacheDirectoryURL:diskCachePathClosure:﹚", message: "Use `init(name:cacheDirectoryURL:diskCachePathClosure:﹚` instead") public convenience init( name: String, path: String?, diskCachePathClosure: DiskCachePathClosure? = nil) throws
Parameters
name
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.path
Location of cache URL on disk. It will be internally pass to the initializer of
DiskStorage
as the disk cache directory.diskCachePathClosure
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.
-
The largest cache cost of memory cache. The total cost is pixel count of all cached images in memory. Default is unlimited. Memory cache will be purged automatically when a memory warning notification is received.
Declaration
Swift
@available(*, deprecated, renamed: "memoryStorage.config.totalCostLimit", message: "Use `memoryStorage.config.totalCostLimit` instead.") open var maxMemoryCost: Int { get set }
-
The default DiskCachePathClosure
Declaration
Swift
@available(*, deprecated, message: "Not needed anymore.") public final class func defaultDiskCachePathClosure(path: String?, cacheName: String) -> String
-
The default file extension appended to cached files.
Declaration
Swift
@available(*, deprecated, renamed: "diskStorage.config.pathExtension", message: "Use `diskStorage.config.pathExtension` instead.") open var pathExtension: String? { get set }
-
The disk cache location.
Declaration
Swift
@available(*, deprecated, renamed: "diskStorage.directoryURL.absoluteString", message: "Use `diskStorage.directoryURL.absoluteString` instead.") public var diskCachePath: String { get }
-
The largest disk size can be taken for the cache. It is the total allocated size of cached files in bytes. Default is no limit.
Declaration
Swift
@available(*, deprecated, renamed: "diskStorage.config.sizeLimit", message: "Use `diskStorage.config.sizeLimit` instead.") open var maxDiskCacheSize: UInt { get set }
-
Undocumented
Declaration
Swift
open func cachePath(forComputedKey key: String) -> String
-
Get an image for a key from disk.
Declaration
Swift
@available(*, deprecated, renamed: "retrieveImageInDiskCache(forKey:options:callbackQueue:completionHandler:﹚", message: "Use `Result` based `retrieveImageInDiskCache(forKey:options:callbackQueue:completionHandler:﹚` instead.") open func retrieveImageInDiskCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image?
Parameters
key
Key for the image.
options
Options of retrieving image. If you need to retrieve an image which was stored with a specified
ImageProcessor
, pass the processor in the option too.Return Value
The image object if it is cached, or
nil
if there is no such key in the cache. -
Undocumented
Declaration
Swift
open func retrieveImage(forKey key: String, options: KingfisherOptionsInfo?, completionHandler: ((Image?, CacheType) -> Void)?)
-
The longest time duration in second of the cache being stored in disk. Default is 1 week (60 * 60 * 24 * 7 seconds). Setting this to a negative value will make the disk cache never expiring.
Declaration
Swift
@available(*, deprecated, message: "Deprecated. Use `diskStorage.config.expiration` instead") open var maxCachePeriodInSecond: TimeInterval { get set }
-
Undocumented
Declaration
Swift
open func store(_ image: Image, original: Data? = nil, forKey key: String, processorIdentifier identifier: String = "", cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default, toDisk: Bool = true, completionHandler: (() -> Void)?)
-
Undocumented
Declaration
Swift
open func calculateDiskCacheSize(completion handler: @escaping ((_ size: UInt) -> Void))