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.

Singleton

  • 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.

    Declaration

    Swift

    public static let `default`: ImageCache

Public Properties

  • 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.

    Declaration

    Swift

    public let memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>
  • 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.

    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

Initializers

  • Creates an ImageCache from a customized MemoryStorage and DiskStorage.

    Declaration

    Swift

    public init(
        memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>,
        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 given name. Both MemoryStorage and DiskStorage will be created with a default config based on the name.

    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. The name should not be an empty string.

  • Creates an ImageCache with a given name, cache directory path 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. If nil, 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.

Storing Images

Removing Images

  • 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 is true.

    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 is true.

    callbackQueue

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

    completionHandler

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

Getting Images

Cleaning

  • 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()

Image Cache State

  • 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.

    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 of DefaultImageProcessor.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 and identifier 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, use imageCachedType(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 of DefaultImageProcessor.default.

    Return Value

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

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

    Note

    By default, for a given combination of key and identifier, 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 of DefaultImageProcessor.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 of DefaultImageProcessor.default.

    Return Value

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

For App Extensions

  • Creates an ImageCache with a given name, cache directory path 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.

Deprecated

  • 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) -> KFCrossPlatformImage?

    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: ((KFCrossPlatformImage?, 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: KFCrossPlatformImage,
                    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))