Kingfisher Documentation

Protocol KFOption​Setter

public protocol KFOptionSetter  
%187 KFOptionSetter KFOptionSetter KFImageProtocol KFImageProtocol KFImageProtocol->KFOptionSetter KF.Builder KF.Builder KF.Builder->KFOptionSetter

Types Conforming to KFOption​Setter

KF.Builder

A builder class to configure an image retrieving task and set it to a holder view or component.

KFImageProtocol

Default Implementations

on​Progress(_:​)

public func onProgress(_ block: DownloadProgressBlock?) -> Self  

Sets the progress block to current builder.

Parameters

block Download​Progress​Block?

Called when the image downloading progress gets updated. If the response does not contain an expectedContentLength, this block will not be called. If block is nil, the callback will be reset.

Returns

A Self value with changes applied.

on​Success(_:​)

public func onSuccess(_ block: ((RetrieveImageResult) -> Void)?) -> Self  

Sets the the done block to current builder.

Parameters

block ((Retrieve​Image​Result) -> Void)?

Called when the image task successfully completes and the the image set is done. If block is nil, the callback will be reset.

Returns

A KF.Builder with changes applied.

on​Failure(_:​)

public func onFailure(_ block: ((KingfisherError) -> Void)?) -> Self  

Sets the catch block to current builder.

Parameters

block ((Kingfisher​Error) -> Void)?

Called when an error happens during the image task. If block is nil, the callback will be reset.

Returns

A KF.Builder with changes applied.

target​Cache(_:​)

public func targetCache(_ cache: ImageCache) -> Self  

Sets the target image cache for this task.

Kingfisher will use the associated ImageCache object when handling related operations, including trying to retrieve the cached images and store the downloaded image to it.

Parameters

cache Image​Cache

The target cache is about to be used for the task.

Returns

A Self value with changes applied.

original​Cache(_:​)

public func originalCache(_ cache: ImageCache) -> Self  

Sets the target image cache to store the original downloaded image for this task.

The ImageCache for storing and retrieving original images. If originalCache is contained in the options, it will be preferred for storing and retrieving original images. If there is no .originalCache in the options, .targetCache will be used to store original images.

When using KingfisherManager to download and store an image, if cacheOriginalImage is applied in the option, the original image will be stored to this originalCache. At the same time, if a requested final image (with processor applied) cannot be found in targetCache, Kingfisher will try to search the original image to check whether it is already there. If found, it will be used and applied with the given processor. It is an optimization for not downloading the same image for multiple times.

Parameters

cache Image​Cache

The target cache is about to be used for storing the original downloaded image from the task.

Returns

A Self value with changes applied.

downloader(_:​)

public func downloader(_ downloader: ImageDownloader) -> Self  

Sets the downloader used to perform the image download task.

Kingfisher will use the set ImageDownloader object to download the requested images.

Parameters

downloader Image​Downloader

The downloader which is about to be used for downloading.

Returns

A Self value with changes applied.

download​Priority(_:​)

public func downloadPriority(_ priority: Float) -> Self  

Sets the download priority for the image task.

The priority value will be set as the priority of the image download task. The value for it should be between 0.0~1.0. You can choose a value between URLSessionTask.defaultPriority, URLSessionTask.lowPriority or URLSessionTask.highPriority. If this option not set, the default value (URLSessionTask.defaultPriority) will be used.

Parameters

priority Float

The download priority of image download task.

Returns

A Self value with changes applied.

force​Refresh(_:​)

public func forceRefresh(_ enabled: Bool = true) -> Self  

Sets whether Kingfisher should ignore the cache and try to start a download task for the image source.

Parameters

enabled Bool

Enable the force refresh or not.

Returns

A Self value with changes applied.

from​Memory​Cache​OrRefresh(_:​)

public func fromMemoryCacheOrRefresh(_ enabled: Bool = true) -> Self  

Sets whether Kingfisher should try to retrieve the image from memory cache first. If not found, it ignores the disk cache and starts a download task for the image source.

This is useful when you want to display a changeable image behind the same url at the same app session, while avoiding download it for multiple times.

Parameters

enabled Bool

Enable the memory-only cache searching or not.

Returns

A Self value with changes applied.

cache​Memory​Only(_:​)

public func cacheMemoryOnly(_ enabled: Bool = true) -> Self  

Sets whether the image should only be cached in memory but not in disk.

Parameters

enabled Bool

Whether the image should be only cache in memory or not.

Returns

A Self value with changes applied.

wait​For​Cache(_:​)

public func waitForCache(_ enabled: Bool = true) -> Self  

Sets whether Kingfisher should wait for caching operation to be completed before calling the onSuccess or onFailure block.

Parameters

enabled Bool

Whether Kingfisher should wait for caching operation.

Returns

A Self value with changes applied.

only​From​Cache(_:​)

public func onlyFromCache(_ enabled: Bool = true) -> Self  

Sets whether Kingfisher should only try to retrieve the image from cache, but not from network.

If the image is not in cache, the image retrieving will fail with the KingfisherError.cacheError with .imageNotExisting as its reason.

Parameters

enabled Bool

Whether Kingfisher should only try to retrieve the image from cache.

Returns

A Self value with changes applied.

background​Decode(_:​)

public func backgroundDecode(_ enabled: Bool = true) -> Self  

Sets whether the image should be decoded in a background thread before using.

Setting to true will decode the downloaded image data and do a off-screen rendering to extract pixel information in background. This can speed up display, but will cost more time and memory to prepare the image for using.

Parameters

enabled Bool

Whether the image should be decoded in a background thread before using.

Returns

A Self value with changes applied.

callback​Queue(_:​)

public func callbackQueue(_ queue: CallbackQueue) -> Self  

Sets the callback queue which is used as the target queue of dispatch callbacks when retrieving images from cache. If not set, Kingfisher will use main queue for callbacks.

Parameters

queue Callback​Queue

The target queue which the cache retrieving callback will be invoked on.

Returns

A Self value with changes applied.

scale​Factor(_:​)

public func scaleFactor(_ factor: CGFloat) -> Self  

Sets the scale factor value when converting retrieved data to an image.

Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at scale 1.0.

Parameters

factor CGFloat

The scale factor value.

Returns

A Self value with changes applied.

cache​Original​Image(_:​)

public func cacheOriginalImage(_ enabled: Bool = true) -> Self  

Sets whether the original image should be cached even when the original image has been processed by any other ImageProcessors.

If set and an ImageProcessor is used, Kingfisher will try to cache both the final result and original image. Kingfisher will have a chance to use the original image when another processor is applied to the same resource, instead of downloading it again. You can use .originalCache to specify a cache or the original images if necessary.

The original image will be only cached to disk storage.

Parameters

enabled Bool

Whether the original image should be cached.

Returns

A Self value with changes applied.

load​Disk​File​Synchronously(_:​)

public func loadDiskFileSynchronously(_ enabled: Bool = true) -> Self  

Sets whether the disk storage loading should happen in the same calling queue.

By default, disk storage file loading happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk loading performance, it also causes a flickering when you reload an image from disk, if the image view already has an image set.

Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance.

Parameters

enabled Bool

Whether the disk storage loading should happen in the same calling queue.

Returns

A Self value with changes applied.

processing​Queue(_:​)

public func processingQueue(_ queue: CallbackQueue?) -> Self  

Sets a queue on which the image processing should happen.

By default, Kingfisher uses a pre-defined serial queue to process images. Use this option to change this behavior. For example, specify a .mainCurrentOrAsync to let the image be processed in main queue to prevent a possible flickering (but with a possibility of blocking the UI, especially if the processor needs a lot of time to run).

Parameters

queue Callback​Queue?

The queue on which the image processing should happen.

Returns

A Self value with changes applied.

alternative​Sources(_:​)

public func alternativeSources(_ sources: [Source]?) -> Self  

Sets the alternative sources that will be used when loading of the original input Source fails.

Values of the sources array will be used to start a new image loading task if the previous task fails due to an error. The image source loading process will stop as soon as a source is loaded successfully. If all sources are used but the loading is still failing, an imageSettingError with alternativeSourcesExhausted as its reason will be given out in the catch block.

This is useful if you want to implement a fallback solution for setting image.

User cancellation will not trigger the alternative source loading.

Parameters

sources [Source]?

The alternative sources will be used.

Returns

A Self value with changes applied.

retry(_:​)

public func retry(_ strategy: RetryStrategy) -> Self  

Sets a retry strategy that will be used when something gets wrong during the image retrieving.

Parameters

strategy Retry​Strategy

The provided strategy to define how the retrying should happen.

Returns

A Self value with changes applied.

retry(max​Count:​interval:​)

public func retry(maxCount: Int, interval: DelayRetryStrategy.Interval = .seconds(3)) -> Self  

Sets a retry strategy with a max retry count and retrying interval.

This defines the simplest retry strategy, which retry a failing request for several times, with some certain interval between each time. For example, .retry(maxCount: 3, interval: .second(3)) means attempt for at most three times, and wait for 3 seconds if a previous retry attempt fails, then start a new attempt.

Parameters

max​Count Int

The maximum count before the retry stops.

interval Delay​Retry​Strategy.​Interval

The time interval between each retry attempt.

Returns

A Self value with changes applied.

low​Data​Mode​Source(_:​)

public func lowDataModeSource(_ source: Source?) -> Self  

Sets the Source should be loaded when user enables Low Data Mode and the original source fails with an NSURLErrorNetworkUnavailableReason.constrained error.

When this option is set, the allowsConstrainedNetworkAccess property of the request for the original source will be set to false and the Source in associated value will be used to retrieve the image for low data mode. Usually, you can provide a low-resolution version of your image or a local image provider to display a placeholder.

If not set or the source is nil, the device Low Data Mode will be ignored and the original source will be loaded following the system default behavior, in a normal way.

Parameters

source Source?

The Source will be loaded under low data mode.

Returns

A Self value with changes applied.

force​Transition(_:​)

public func forceTransition(_ enabled: Bool = true) -> Self  

Sets whether the image setting for an image view should happen with transition even when retrieved from cache.

Parameters

enabled Bool

Enable the force transition or not.

Returns

A KF.Builder with changes applied.

request​Modifier(_:​)

public func requestModifier(_ modifier: ImageDownloadRequestModifier) -> Self  

Sets an ImageDownloadRequestModifier to change the image download request before it being sent.

This is the last chance you can modify the image download request. You can modify the request for some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping.

Parameters

modifier Image​Download​Request​Modifier

The modifier will be used to change the request before it being sent.

Returns

A Self value with changes applied.

request​Modifier(_:​)

public func requestModifier(_ modifyBlock: @escaping (inout URLRequest) -> Void) -> Self  

Sets a block to change the image download request before it being sent.

This is the last chance you can modify the image download request. You can modify the request for some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping.

Parameters

modify​Block @escaping (inout URLRequest) -> Void

The modifying block will be called to change the request before it being sent.

Returns

A Self value with changes applied.

redirect​Handler(_:​)

public func redirectHandler(_ handler: ImageDownloadRedirectHandler) -> Self  

The ImageDownloadRedirectHandler argument will be used to change the request before redirection. This is the possibility you can modify the image download request during redirect. You can modify the request for some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. The original redirection request will be sent without any modification by default.

Parameters

handler Image​Download​Redirect​Handler

The handler will be used for redirection.

Returns

A Self value with changes applied.

redirect​Handler(_:​)

public func redirectHandler(_ block: @escaping (KF.RedirectPayload) -> Void) -> Self  

The block will be used to change the request before redirection. This is the possibility you can modify the image download request during redirect. You can modify the request for some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. The original redirection request will be sent without any modification by default.

Parameters

block @escaping (KF.​Redirect​Payload) -> Void

The block will be used for redirection.

Returns

A Self value with changes applied.

set​Processor(_:​)

public func setProcessor(_ processor: ImageProcessor) -> Self  

Sets an image processor for the image task. It replaces the current image processor settings.

Parameters

processor Image​Processor

The processor you want to use to process the image after it is downloaded.

Returns

A Self value with changes applied.

set​Processors(_:​)

public func setProcessors(_ processors: [ImageProcessor]) -> Self  

Sets an array of image processors for the image task. It replaces the current image processor settings.

Parameters

processors [Image​Processor]

An array of processors. The processors inside this array will be concatenated one by one to form a processor pipeline.

Returns

A Self value with changes applied.

append​Processor(_:​)

public func appendProcessor(_ processor: ImageProcessor) -> Self  

Appends a processor to the current set processors.

Parameters

processor Image​Processor

The processor which will be appended to current processor settings.

Returns

A Self value with changes applied.

round​Corner(radius:​target​Size:​rounding​Corners:​background​Color:​)

public func roundCorner(
        radius: RoundCornerImageProcessor.Radius,
        targetSize: CGSize? = nil,
        roundingCorners corners: RectCorner = .all,
        backgroundColor: KFCrossPlatformColor? = nil
    ) -> Self

Appends a RoundCornerImageProcessor to current processors.

Parameters

radius Round​Corner​Image​Processor.​Radius

The radius will be applied in processing. Specify a certain point value with .point, or a fraction of the target image with .widthFraction. or .heightFraction. For example, given a square image with width and height equals, .widthFraction(0.5) means use half of the length of size and makes the final image a round one.

target​Size CGSize?

Target size of output image should be. If nil, the image will keep its original size after processing.

corners Rect​Corner

The target corners which will be applied rounding.

background​Color KFCross​Platform​Color?

Background color of the output image. If nil, it will use a transparent background.

Returns

A Self value with changes applied.

blur(radius:​)

public func blur(radius: CGFloat) -> Self  

Appends a BlurImageProcessor to current processors.

Parameters

radius CGFloat

Blur radius for the simulated Gaussian blur.

Returns

A Self value with changes applied.

overlay(color:​fraction:​)

public func overlay(color: KFCrossPlatformColor, fraction: CGFloat = 0.5) -> Self  

Appends a OverlayImageProcessor to current processors.

Parameters

color KFCross​Platform​Color

Overlay color will be used to overlay the input image.

fraction CGFloat

Fraction will be used when overlay the color to image.

Returns

A Self value with changes applied.

tint(color:​)

public func tint(color: KFCrossPlatformColor) -> Self  

Appends a TintImageProcessor to current processors.

Parameters

color KFCross​Platform​Color

Tint color will be used to tint the input image.

Returns

A Self value with changes applied.

black​White()

public func blackWhite() -> Self  

Appends a BlackWhiteProcessor to current processors.

Returns

A Self value with changes applied.

cropping(size:​anchor:​)

public func cropping(size: CGSize, anchor: CGPoint = .init(x: 0.5, y: 0.5)) -> Self  

Appends a CroppingImageProcessor to current processors.

Parameters

size CGSize

Target size of output image should be.

anchor CGPoint

Anchor point from which the output size should be calculate. The anchor point is consisted by two values between 0.0 and 1.0. It indicates a related point in current image. See CroppingImageProcessor.init(size:anchor:) for more.

Returns

A Self value with changes applied.

downsampling(size:​)

public func downsampling(size: CGSize) -> Self  

Appends a DownsamplingImageProcessor to current processors.

Compared to ResizingImageProcessor, the DownsamplingImageProcessor does not render the original images and then resize it. Instead, it downsamples the input data directly to a thumbnail image. So it is a more efficient than ResizingImageProcessor. Prefer to use DownsamplingImageProcessor as possible as you can than the ResizingImageProcessor.

Only CG-based images are supported. Animated images (like GIF) is not supported.

Parameters

size CGSize

Target size of output image should be. It should be smaller than the size of input image. If it is larger, the result image will be the same size of input data without downsampling.

Returns

A Self value with changes applied.

resizing(reference​Size:​mode:​)

public func resizing(referenceSize: CGSize, mode: ContentMode = .none) -> Self  

Appends a ResizingImageProcessor to current processors.

If you need to resize a data represented image to a smaller size, use DownsamplingImageProcessor instead, which is more efficient and uses less memory.

Parameters

reference​Size CGSize

The reference size for resizing operation in point.

mode Content​Mode

Target content mode of output image should be. Default is .none.

Returns

A Self value with changes applied.

serialize(by:​)

public func serialize(by cacheSerializer: CacheSerializer) -> Self  

Uses a given CacheSerializer to convert some data to an image object for retrieving from disk cache or vice versa for storing to disk cache.

Parameters

cache​Serializer Cache​Serializer

The CacheSerializer which will be used.

Returns

A Self value with changes applied.

serialize(as:​jpeg​Compression​Quality:​)

public func serialize(as format: ImageFormat, jpegCompressionQuality: CGFloat? = nil) -> Self  

Uses a given format to serializer the image data to disk. It converts the image object to the give data format.

Parameters

format Image​Format

The desired data encoding format when store the image on disk.

jpeg​Compression​Quality CGFloat?

If the format is .JPEG, it specify the compression quality when converting the image to a JPEG data. Otherwise, it is ignored.

Returns

A Self value with changes applied.

image​Modifier(_:​)

public func imageModifier(_ modifier: ImageModifier?) -> Self  

Sets an ImageModifier to the image task. Use this to modify the fetched image object properties if needed.

If the image was fetched directly from the downloader, the modifier will run directly after the ImageProcessor. If the image is being fetched from a cache, the modifier will run after the CacheSerializer.

Parameters

modifier Image​Modifier?

The ImageModifier which will be used to modify the image object.

Returns

A Self value with changes applied.

image​Modifier(_:​)

public func imageModifier(_ block: @escaping (inout KFCrossPlatformImage) throws -> Void) -> Self  

Sets a block to modify the image object. Use this to modify the fetched image object properties if needed.

If the image was fetched directly from the downloader, the modifier block will run directly after the ImageProcessor. If the image is being fetched from a cache, the modifier will run after the CacheSerializer.

Parameters

block @escaping (inout KFCross​Platform​Image) throws -> Void

The block which is used to modify the image object.

Returns

A Self value with changes applied.

memory​Cache​Expiration(_:​)

public func memoryCacheExpiration(_ expiration: StorageExpiration?) -> Self  

Sets the expiration setting for memory cache of this image task.

By default, the underlying MemoryStorage.Backend uses the expiration in its config for all items. If set, the MemoryStorage.Backend will use this value to overwrite the config setting for this caching item.

Parameters

expiration Storage​Expiration?

The expiration setting used in cache storage.

Returns

A Self value with changes applied.

memory​Cache​Access​Extending(_:​)

public func memoryCacheAccessExtending(_ extending: ExpirationExtending) -> Self  

Sets the expiration extending setting for memory cache. The item expiration time will be incremented by this value after access.

By default, the underlying MemoryStorage.Backend uses the initial cache expiration as extending value: .cacheTime.

To disable extending option at all, sets .none to it.

Parameters

extending Expiration​Extending

The expiration extending setting used in cache storage.

Returns

A Self value with changes applied.

disk​Cache​Expiration(_:​)

public func diskCacheExpiration(_ expiration: StorageExpiration?) -> Self  

Sets the expiration setting for disk cache of this image task.

By default, the underlying DiskStorage.Backend uses the expiration in its config for all items. If set, the DiskStorage.Backend will use this value to overwrite the config setting for this caching item.

Parameters

expiration Storage​Expiration?

The expiration setting used in cache storage.

Returns

A Self value with changes applied.

disk​Cache​Access​Extending(_:​)

public func diskCacheAccessExtending(_ extending: ExpirationExtending) -> Self  

Sets the expiration extending setting for disk cache. The item expiration time will be incremented by this value after access.

By default, the underlying DiskStorage.Backend uses the initial cache expiration as extending value: .cacheTime.

To disable extending option at all, sets .none to it.

Parameters

extending Expiration​Extending

The expiration extending setting used in cache storage.

Returns

A Self value with changes applied.

Requirements

options

on​Failure​Delegate

var onFailureDelegate: Delegate<KingfisherError, Void>  

on​Success​Delegate

var onSuccessDelegate: Delegate<RetrieveImageResult, Void>  

on​Progress​Delegate

var onProgressDelegate: Delegate<(Int64, Int64), Void>  

delegate​Observer

var delegateObserver: AnyObject