diff --git a/Sources/Cache/Storage.swift b/Sources/Cache/Storage.swift index ad9d32632..05128c703 100644 --- a/Sources/Cache/Storage.swift +++ b/Sources/Cache/Storage.swift @@ -91,7 +91,7 @@ public enum StorageExpiration { public enum ExpirationExtending { /// The item expires after the original time, without extending after access. case none - /// The item expiration extends by the original cache time after each access. + /// The item expiration extends to the original cache time after each access. case cacheTime /// The item expiration extends by the provided time after each access. case expirationTime(_ expiration: StorageExpiration) diff --git a/Sources/General/ImageSource/Resource.swift b/Sources/General/ImageSource/Resource.swift index 3f0b77419..b841889a4 100644 --- a/Sources/General/ImageSource/Resource.swift +++ b/Sources/General/ImageSource/Resource.swift @@ -47,6 +47,7 @@ extension Resource { /// - Parameter overrideCacheKey: The key should be used to override the ``Resource/cacheKey`` when performing the /// conversion. `nil` if not overriden and ``Resource/cacheKey`` of `self` is used. /// - Returns: The converted source. + /// public func convertToSource(overrideCacheKey: String? = nil) -> Source { let key = overrideCacheKey ?? cacheKey return downloadURL.isFileURL ? @@ -74,6 +75,7 @@ extension KF { /// - cacheKey: /// The cache key. If `nil`, Kingfisher will use the `absoluteString` of ``ImageResource/downloadURL`` as /// the key. Default is `nil`. + /// public init(downloadURL: URL, cacheKey: String? = nil) { self.downloadURL = downloadURL self.cacheKey = cacheKey ?? downloadURL.cacheKey diff --git a/Sources/General/ImageSource/Source.swift b/Sources/General/ImageSource/Source.swift index 645a0b4b5..c84e5ab8b 100644 --- a/Sources/General/ImageSource/Source.swift +++ b/Sources/General/ImageSource/Source.swift @@ -26,14 +26,16 @@ import Foundation + /// Represents an image source setting for Kingfisher methods. /// -/// A `Source` value indicates the way in which the target image can be retrieved and cached. +/// A ``Source`` value indicates the way in which the target image can be retrieved and cached. /// -/// - network: The target image should be retrieved from the network remotely. The associated ``Resource`` +/// - `network`: The target image should be retrieved from the network remotely. The associated ``Resource`` /// value defines detailed information like image URL and cache key. -/// - provider: The target image should be provided in a data format. Normally, it can be an image +/// - `provider`: The target image should be provided in a data format. Normally, it can be an image /// from local storage or in any other encoding format (like Base64). +/// public enum Source { /// Represents the source task identifier when setting an image to a view with extension methods. diff --git a/Sources/General/KingfisherError.swift b/Sources/General/KingfisherError.swift index c6e79145e..6f785e1de 100644 --- a/Sources/General/KingfisherError.swift +++ b/Sources/General/KingfisherError.swift @@ -33,209 +33,288 @@ import UIKit extension Never {} -/// Represents all the errors which can happen in Kingfisher framework. -/// Kingfisher related methods always throw a `KingfisherError` or invoke the callback with `KingfisherError` +/// Represents all the errors that can occur in the Kingfisher framework. +/// +/// Kingfisher-related methods always throw a ``KingfisherError`` or invoke the callback with ``KingfisherError`` /// as its error type. To handle errors from Kingfisher, you switch over the error to get a reason catalog, -/// then switch over the reason to know error detail. +/// then switch over the reason to understand the error details. +/// public enum KingfisherError: Error { // MARK: Error Reason Types - /// Represents the error reason during networking request phase. - /// - /// - emptyRequest: The request is empty. Code 1001. - /// - invalidURL: The URL of request is invalid. Code 1002. - /// - taskCancelled: The downloading task is cancelled by user. Code 1003. + /// Represents the error reasons during the networking request phase. public enum RequestErrorReason { - /// The request is empty. Code 1001. + /// The request is empty. + /// + /// Error Code: 1001 case emptyRequest - /// The URL of request is invalid. Code 1002. - /// - request: The request is tend to be sent but its URL is invalid. + /// The URL of the request is invalid. + /// + /// - Parameter request: The request is intended to be sent, but its URL is invalid. + /// + /// Error Code: 1002 case invalidURL(request: URLRequest) - - /// The downloading task is cancelled by user. Code 1003. - /// - task: The session data task which is cancelled. - /// - token: The cancel token which is used for cancelling the task. + + /// The downloading task is canceled by the user. + /// + /// - Parameters: + /// - task: The session data task which is canceled. + /// - token: The cancel token which is used for canceling the task. + /// + /// Error Code: 1003 case taskCancelled(task: SessionDataTask, token: SessionDataTask.CancelToken) } /// Represents the error reason during networking response phase. - /// - /// - invalidURLResponse: The response is not a valid URL response. Code 2001. - /// - invalidHTTPStatusCode: The response contains an invalid HTTP status code. Code 2002. - /// - URLSessionError: An error happens in the system URL session. Code 2003. - /// - dataModifyingFailed: Data modifying fails on returning a valid data. Code 2004. - /// - noURLResponse: The task is done but no URL response found. Code 2005. public enum ResponseErrorReason { - /// The response is not a valid URL response. Code 2001. - /// - response: The received invalid URL response. - /// The response is expected to be an HTTP response, but it is not. + /// The response is not a valid URL response. + /// + /// - Parameters: + /// - response: The received invalid URL response. + /// The response is expected to be an HTTP response, but it is not. + /// + /// Error Code: 2001 case invalidURLResponse(response: URLResponse) - /// The response contains an invalid HTTP status code. Code 2002. - /// - Note: - /// By default, status code 200..<400 is recognized as valid. You can override + /// The response contains an invalid HTTP status code. + /// + /// - Parameters: + /// - response: The received response. + /// + /// Error Code: 2002 + /// + /// - Note: By default, status code 200..<400 is recognized as valid. You can override /// this behavior by conforming to the `ImageDownloaderDelegate`. - /// - response: The received response. case invalidHTTPStatusCode(response: HTTPURLResponse) - /// An error happens in the system URL session. Code 2003. - /// - error: The underlying URLSession error object. + /// An error happens in the system URL session. + /// + /// - Parameters: + /// - error: The underlying URLSession error object. + /// + /// Error Code: 2003 case URLSessionError(error: Error) - /// Data modifying fails on returning a valid data. Code 2004. - /// - task: The failed task. + /// Data modifying fails on returning a valid data. + /// + /// - Parameters: + /// - task: The failed task. + /// + /// Error Code: 2004 case dataModifyingFailed(task: SessionDataTask) - /// The task is done but no URL response found. Code 2005. - /// - task: The failed task. + /// The task is done but no URL response found. + /// + /// - Parameters: + /// - task: The failed task. + /// + /// Error Code: 2005 case noURLResponse(task: SessionDataTask) - /// The task is cancelled by `ImageDownloaderDelegate` due to the `.cancel` response disposition is - /// specified by the delegate method. Code 2006. + /// The task is cancelled by ``ImageDownloaderDelegate`` due to the `.cancel` response disposition is + /// specified by the delegate method. + /// + /// - Parameters: + /// - task: The cancelled task. + /// + /// Error Code: 2006 case cancelledByDelegate(response: URLResponse) } - /// Represents the error reason during Kingfisher caching system. - /// - /// - fileEnumeratorCreationFailed: Cannot create a file enumerator for a certain disk URL. Code 3001. - /// - invalidFileEnumeratorContent: Cannot get correct file contents from a file enumerator. Code 3002. - /// - invalidURLResource: The file at target URL exists, but its URL resource is unavailable. Code 3003. - /// - cannotLoadDataFromDisk: The file at target URL exists, but the data cannot be loaded from it. Code 3004. - /// - cannotCreateDirectory: Cannot create a folder at a given path. Code 3005. - /// - imageNotExisting: The requested image does not exist in cache. Code 3006. - /// - cannotConvertToData: Cannot convert an object to data for storing. Code 3007. - /// - cannotSerializeImage: Cannot serialize an image to data for storing. Code 3008. - /// - cannotCreateCacheFile: Cannot create the cache file at a certain fileURL under a key. Code 3009. - /// - cannotSetCacheFileAttribute: Cannot set file attributes to a cached file. Code 3010. + /// Represents the error reason during Kingfisher caching. public enum CacheErrorReason { - /// Cannot create a file enumerator for a certain disk URL. Code 3001. - /// - url: The target disk URL from which the file enumerator should be created. + /// Cannot create a file enumerator for a certain disk URL. + /// + /// - Parameters: + /// - url: The target disk URL from which the file enumerator should be created. + /// + /// Error Code: 3001 case fileEnumeratorCreationFailed(url: URL) - /// Cannot get correct file contents from a file enumerator. Code 3002. - /// - url: The target disk URL from which the content of a file enumerator should be got. + /// Cannot get correct file contents from a file enumerator. + /// + /// - Parameters: + /// - url: The target disk URL from which the content of a file enumerator should be obtained. + /// + /// Error Code: 3002 case invalidFileEnumeratorContent(url: URL) - /// The file at target URL exists, but its URL resource is unavailable. Code 3003. - /// - error: The underlying error thrown by file manager. - /// - key: The key used to getting the resource from cache. - /// - url: The disk URL where the target cached file exists. + /// The file at the target URL exists, but its URL resource is unavailable. + /// + /// - Parameters: + /// - error: The underlying error thrown by the file manager. + /// - key: The key used to retrieve the resource from cache. + /// - url: The disk URL where the target cached file exists. + /// + /// Error Code: 3003 case invalidURLResource(error: Error, key: String, url: URL) - /// The file at target URL exists, but the data cannot be loaded from it. Code 3004. - /// - url: The disk URL where the target cached file exists. - /// - error: The underlying error which describes why this error happens. + /// The file at the target URL exists, but the data cannot be loaded from it. + /// + /// - Parameters: + /// - url: The disk URL where the target cached file exists. + /// - error: The underlying error that describes why this error occurs. + /// + /// Error Code: 3004 case cannotLoadDataFromDisk(url: URL, error: Error) - /// Cannot create a folder at a given path. Code 3005. - /// - path: The disk path where the directory creating operation fails. - /// - error: The underlying error which describes why this error happens. + /// Cannot create a folder at a given path. + /// + /// - Parameters: + /// - path: The disk path where the directory creation operation fails. + /// - error: The underlying error that describes why this error occurs. + /// + /// Error Code: 3005 case cannotCreateDirectory(path: String, error: Error) - /// The requested image does not exist in cache. Code 3006. - /// - key: Key of the requested image in cache. + /// The requested image does not exist in the cache. + /// + /// - Parameters: + /// - key: The key of the requested image in the cache. + /// + /// Error Code: 3006 case imageNotExisting(key: String) - /// Cannot convert an object to data for storing. Code 3007. - /// - object: The object which needs be convert to data. + /// Unable to convert an object to data for storage. + /// + /// - Parameters: + /// - object: The object that needs to be converted to data. + /// + /// Error Code: 3007 case cannotConvertToData(object: Any, error: Error) - /// Cannot serialize an image to data for storing. Code 3008. - /// - image: The input image needs to be serialized to cache. - /// - original: The original image data, if exists. - /// - serializer: The `CacheSerializer` used for the image serializing. + /// Unable to serialize an image to data for storage. + /// + /// - Parameters: + /// - image: The input image that needs to be serialized to cache. + /// - original: The original image data, if it exists. + /// - serializer: The ``CacheSerializer`` used for the image serialization. + /// + /// Error Code: 3008 case cannotSerializeImage(image: KFCrossPlatformImage?, original: Data?, serializer: CacheSerializer) - /// Cannot create the cache file at a certain fileURL under a key. Code 3009. - /// - fileURL: The url where the cache file should be created. - /// - key: The cache key used for the cache. When caching a file through `KingfisherManager` and Kingfisher's - /// extension method, it is the resolved cache key based on your input `Source` and the image processors. - /// - data: The data to be cached. - /// - error: The underlying error originally thrown by Foundation when writing the `data` to the disk file at - /// `fileURL`. + /// Unable to create the cache file at a specified `fileURL` under a given `key`. + /// + /// - Parameters: + /// - fileURL: The URL where the cache file should be created. + /// - key: The cache key used for the cache. When caching a file through ``KingfisherManager`` and Kingfisher's + /// extension method, it is the resolved cache key based on your input ``Source`` and the image + /// processors. + /// - data: The data to be cached. + /// - error: The underlying error originally thrown by Foundation when attempting to write the `data` to the disk file at + /// `fileURL`. + /// + /// Error Code: 3009 case cannotCreateCacheFile(fileURL: URL, key: String, data: Data, error: Error) - /// Cannot set file attributes to a cached file. Code 3010. - /// - filePath: The path of target cache file. - /// - attributes: The file attribute to be set to the target file. - /// - error: The underlying error originally thrown by Foundation when setting the `attributes` to the disk - /// file at `filePath`. + /// Unable to set file attributes for a cached file. + /// + /// - Parameters: + /// - filePath: The path of the target cache file. + /// - attributes: The file attributes to be set for the target file. + /// - error: The underlying error originally thrown by the Foundation framework when attempting to set the specified + /// `attributes` for the disk file at `filePath`. + /// + /// Error Code: 3010 case cannotSetCacheFileAttribute(filePath: String, attributes: [FileAttributeKey : Any], error: Error) - /// The disk storage of cache is not ready. Code 3011. + + /// The disk storage for caching is not ready. /// - /// This is usually due to extremely lack of space on disk storage, and - /// Kingfisher failed even when creating the cache folder. The disk storage will be in unusable state. Normally, - /// ask user to free some spaces and restart the app to make the disk storage work again. - /// - cacheURL: The intended URL which should be the storage folder. + /// - Parameters: + /// - cacheURL: The intended URL that should be the storage folder. + /// + /// This issue typically arises due to an extreme lack of space on the disk storage. Kingfisher fails to create + /// the cache folder under these circumstances, rendering the disk storage unusable. In such cases, it is + /// recommended to prompt the user to free up storage space and restart the app to restore functionality. + /// + /// Error Code: 3011 case diskStorageIsNotReady(cacheURL: URL) } /// Represents the error reason during image processing phase. - /// - /// - processingFailed: Image processing fails. There is no valid output image from the processor. Code 4001. public enum ProcessorErrorReason { - /// Image processing fails. There is no valid output image from the processor. Code 4001. - /// - processor: The `ImageProcessor` used to process the image or its data in `item`. - /// - item: The image or its data content. + /// Image processing has failed, and there is no valid output image generated by the processor. + /// + /// - Parameters: + /// - processor: The `ImageProcessor` responsible for processing the image or its data in `item`. + /// - item: The image or its data content. + /// + /// Error Code: 4001 case processingFailed(processor: ImageProcessor, item: ImageProcessItem) } /// Represents the error reason during image setting in a view related class. - /// - /// - emptySource: The input resource is empty or `nil`. Code 5001. - /// - notCurrentSourceTask: The source task is finished, but it is not the one expected now. Code 5002. - /// - dataProviderError: An error happens during getting data from an `ImageDataProvider`. Code 5003. public enum ImageSettingErrorReason { - /// The input resource is empty or `nil`. Code 5001. + /// The input resource is empty or `nil`. + /// + /// Error Code: 5001 case emptySource - /// The resource task is finished, but it is not the one expected now. This usually happens when you set another - /// resource on the view without cancelling the current on-going one. The previous setting task will fail with - /// this `.notCurrentSourceTask` error when a result got, regardless of it being successful or not for that task. - /// The result of this original task is contained in the associated value. - /// Code 5002. - /// - result: The `RetrieveImageResult` if the source task is finished without problem. `nil` if an error - /// happens. - /// - error: The `Error` if an issue happens during image setting task. `nil` if the task finishes without - /// problem. - /// - source: The original source value of the task. + /// The resource task is completed, but it is not the one that was expected. This typically occurs when you set + /// another resource on the view without canceling the current ongoing task. The previous task will fail with the + /// `.notCurrentSourceTask` error when a result is obtained, regardless of whether it was successful or not for + /// that task. + /// + /// - Parameters: + /// - result: The `RetrieveImageResult` if the source task is completed without any issues. `nil` if an error occurred. + /// - error: The `Error` if there was a problem during the image setting task. `nil` if the task completed successfully. + /// - source: The original source value of the task. + /// + /// Error Code: 5002 case notCurrentSourceTask(result: RetrieveImageResult?, error: Error?, source: Source) - /// An error happens during getting data from an `ImageDataProvider`. Code 5003. + /// An error occurs while retrieving data from an `ImageDataProvider`. + /// + /// - Parameters: + /// - provider: The ``ImageDataProvider`` that encountered the error. + /// - error: The underlying error that describes why this error occurred. + /// + /// Error Code: 5003 case dataProviderError(provider: ImageDataProvider, error: Error) - /// No more alternative `Source` can be used in current loading process. It means that the - /// `.alternativeSources` are used and Kingfisher tried to recovery from the original error, but still + /// No more alternative ``Source`` can be used in current loading process. It means that the + /// ``KingfisherOptionsInfoItem/alternativeSources(_:)`` are set and Kingfisher tried to recovery from the original error, but still /// fails for all the given alternative sources. The associated value holds all the errors encountered during /// the load process, including the original source loading error and all the alternative sources errors. /// Code 5004. + + /// No more alternative `Source` can be used in the current loading process. + /// + /// - Parameters: + /// - error : A ``PropagationError`` contains more information about the source and error. + /// + /// This means that the ``KingfisherOptionsInfoItem/alternativeSources(_:)`` option is set, and Kingfisher attempted to recover from the original error, + /// but still failed for all the provided alternative sources. The associated value holds all the errors encountered during + /// the loading process, including the original source loading error and all the alternative sources errors. + /// + /// Error Code: 5004 case alternativeSourcesExhausted([PropagationError]) } // MARK: Member Cases - /// Represents the error reason during networking request phase. + /// Represents the error reasons that can occur during the networking request phase. case requestError(reason: RequestErrorReason) - /// Represents the error reason during networking response phase. + /// Represents the error reason that can occur during networking response phase. case responseError(reason: ResponseErrorReason) - /// Represents the error reason during Kingfisher caching system. + /// Represents the error reason that can occur during Kingfisher caching phase. case cacheError(reason: CacheErrorReason) - /// Represents the error reason during image processing phase. + /// Represents the error reason that can occur during image processing phase. case processorError(reason: ProcessorErrorReason) - /// Represents the error reason during image setting in a view related class. + /// Represents the error reason that can occur during image setting in a view related class. case imageSettingError(reason: ImageSettingErrorReason) // MARK: Helper Properties & Methods - /// Helper property to check whether this error is a `RequestErrorReason.taskCancelled` or not. + /// A helper property to determine if this error is of type `RequestErrorReason.taskCancelled`. public var isTaskCancelled: Bool { if case .requestError(reason: .taskCancelled) = self { return true @@ -243,12 +322,23 @@ public enum KingfisherError: Error { return false } - /// Helper method to check whether this error is a `ResponseErrorReason.invalidHTTPStatusCode` and the - /// associated value is a given status code. + /// Helper method to check whether this error is a ``ResponseErrorReason/invalidHTTPStatusCode(response:)`` + /// and the associated value is a given status code. /// /// - Parameter code: The given status code. /// - Returns: If `self` is a `ResponseErrorReason.invalidHTTPStatusCode` error /// and its status code equals to `code`, `true` is returned. Otherwise, `false`. + /// + + + /// A helper method for checking HTTP status code. + /// + /// Use this helper method to determine whether this error corresponds to a + /// ``ResponseErrorReason/invalidHTTPStatusCode(response:)`` with a specific status code. + /// + /// - Parameter code: The desired HTTP status code for comparison. + /// - Returns: `true` if the error is of type ``ResponseErrorReason/invalidHTTPStatusCode(response:)`` and its + /// status code matches the provided `code`, otherwise `false`. public func isInvalidResponseStatusCode(_ code: Int) -> Bool { if case .responseError(reason: .invalidHTTPStatusCode(let response)) = self { return response.statusCode == code @@ -256,6 +346,8 @@ public enum KingfisherError: Error { return false } + + /// A helper method for checking the error is type of ``ResponseErrorReason/invalidHTTPStatusCode(response:)``. public var isInvalidResponseStatusCode: Bool { if case .responseError(reason: .invalidHTTPStatusCode) = self { return true @@ -263,10 +355,18 @@ public enum KingfisherError: Error { return false } - /// Helper property to check whether this error is a `ImageSettingErrorReason.notCurrentSourceTask` or not. - /// When a new image setting task starts while the old one is still running, the new task identifier will be - /// set and the old one is overwritten. A `.notCurrentSourceTask` error will be raised when the old task finishes - /// to let you know the setting process finishes with a certain result, but the image view or button is not set. + /// A helper property that indicates whether this error is of type + /// ``ImageSettingErrorReason/notCurrentSourceTask(result:error:source:)`` or not. + /// + /// This property is used to check if a new image setting task starts while the old one is still running. + /// In such a scenario, the identifier of the new task will overwrite the identifier of the old task. + /// + /// When the old task finishes, a ``ImageSettingErrorReason/notCurrentSourceTask(result:error:source:)`` error will + /// be raised to notify you that the setting process has completed with a certain result, but the image view or + /// button has not been updated. + /// + /// - Returns: `true` if the error is of type ``ImageSettingErrorReason/notCurrentSourceTask(result:error:source:)``, + /// `false` otherwise. public var isNotCurrentTask: Bool { if case .imageSettingError(reason: .notCurrentSourceTask(_, _, _)) = self { return true @@ -290,7 +390,9 @@ public enum KingfisherError: Error { // MARK: - LocalizedError Conforming extension KingfisherError: LocalizedError { - /// A localized message describing what error occurred. + /// Provides a localized message describing the error that occurred. + /// + /// Use this property to obtain a human-readable description of the error for display to the user. public var errorDescription: String? { switch self { case .requestError(let reason): return reason.errorDescription @@ -306,10 +408,24 @@ extension KingfisherError: LocalizedError { // MARK: - CustomNSError Conforming extension KingfisherError: CustomNSError { - /// The error domain of `KingfisherError`. All errors from Kingfisher is under this domain. + /// The error domain for ``KingfisherError``. All errors generated by Kingfisher are categorized under this domain. + /// + /// When handling errors from the Kingfisher library, you can use this domain to identify and distinguish them + /// from other types of errors in your application. + /// + /// - Note: The error domain is a string identifier associated with each error. public static let domain = "com.onevcat.Kingfisher.Error" - /// The error code within the given domain. + /// Represents the error code within the specified error domain. + /// + /// Use this property to retrieve the specific error code associated with a ``KingfisherError``. The error code + /// provides additional context and information about the error, allowing you to handle and respond to different + /// error scenarios. + /// + /// - Note: Error codes are numerical values associated with each error within a domain. Check the error code in the + /// API reference of each error reason for the detail. + /// + /// - Returns: The error code as an integer. public var errorCode: Int { switch self { case .requestError(let reason): return reason.errorCode diff --git a/Sources/General/KingfisherManager.swift b/Sources/General/KingfisherManager.swift index 1e09daab6..1d344dfdb 100644 --- a/Sources/General/KingfisherManager.swift +++ b/Sources/General/KingfisherManager.swift @@ -32,61 +32,78 @@ import AppKit import UIKit #endif -/// The downloading progress block type. -/// The parameter value is the `receivedSize` of current response. -/// The second parameter is the total expected data length from response's "Content-Length" header. -/// If the expected length is not available, this block will not be called. +/// Represents the type for a downloading progress block. +/// +/// This block type is used to monitor the progress of data being downloaded. It takes two parameters: +/// +/// 1. `receivedSize`: The size of the data received in the current response. +/// 2. `expectedSize`: The total expected data length from the response's "Content-Length" header. If the expected +/// length is not available, this block will not be called. +/// +/// You can use this progress block to track the download progress and update user interfaces or perform additional +/// actions based on the progress. +/// +/// - Parameters: +/// - receivedSize: The size of the data received. +/// - expectedSize: The expected total data length from the "Content-Length" header. public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> Void) -/// Represents the result of a Kingfisher retrieving image task. +/// Represents the result of a Kingfisher image retrieval task. +/// +/// This type encapsulates the outcome of an image retrieval operation performed by Kingfisher. +/// It holds a successful result with the retrieved image. public struct RetrieveImageResult { - /// Gets the image object of this result. + /// Retrieves the image object from this result. public let image: KFCrossPlatformImage - /// Gets the cache source of the image. It indicates from which layer of cache this image is retrieved. - /// If the image is just downloaded from network, `.none` will be returned. + /// Retrieves the cache source of the image, indicating from which cache layer it was retrieved. + /// + /// If the image was freshly downloaded from the network and not retrieved from any cache, `.none` will be returned. + /// Otherwise, either ``CacheType/memory`` or ``CacheType/disk`` will be returned, allowing you to determine whether + /// the image was retrieved from memory or disk cache. public let cacheType: CacheType - /// The `Source` which this result is related to. This indicated where the `image` of `self` is referring. + /// The ``Source`` to which this result is related. This indicates where the `image` referenced by `self` is located. public let source: Source - /// The original `Source` from which the retrieve task begins. It can be different from the `source` property. - /// When an alternative source loading happened, the `source` will be the replacing loading target, while the - /// `originalSource` will be kept as the initial `source` which issued the image loading process. + /// The original ``Source`` from which the retrieval task begins. It may differ from the ``source`` property. + /// When an alternative source loading occurs, the ``source`` will represent the replacement loading target, while the + /// ``originalSource`` will retain the initial ``source`` that initiated the image loading process. public let originalSource: Source - /// Gets the data behind the result. + /// Retrieves the data associated with this result. /// - /// If this result is from a network downloading (when `cacheType == .none`), calling this returns the downloaded - /// data. If the reuslt is from cache, it serializes the image with the given cache serializer in the loading option - /// and returns the result. + /// When this result is obtained from a network download (when `cacheType == .none`), calling this method returns + /// the downloaded data. If the result is from the cache, it serializes the image using the specified cache + /// serializer from the loading options and returns the result. /// - /// - Note: - /// This can be a time-consuming action, so if you need to use the data for multiple times, it is suggested to hold - /// it and prevent keeping calling this too frequently. + /// - Note: Retrieving this data can be a time-consuming operation, so it is advisable to store it if you need to + /// use it multiple times and avoid frequent calls to this method. public let data: () -> Data? } -/// A struct that stores some related information of an `KingfisherError`. It provides some context information for -/// a pure error so you can identify the error easier. +/// A structure that stores related information about a ``KingfisherError``. It provides contextual information +/// to facilitate the identification of the error. public struct PropagationError { - /// The `Source` to which current `error` is bound. + /// The ``Source`` to which current `error` is bound. public let source: Source /// The actual error happens in framework. public let error: KingfisherError } - -/// The downloading task updated block type. The parameter `newTask` is the updated new task of image setting process. -/// It is a `nil` if the image loading does not require an image downloading process. If an image downloading is issued, -/// this value will contain the actual `DownloadTask` for you to keep and cancel it later if you need. +/// The block type used for handling updates during the downloading task. +/// +/// The `newTask` parameter represents the updated task for the image loading process. It is `nil` if the image loading +/// doesn't involve a downloading process. When an image download is initiated, this value will contain the actual +/// ``DownloadTask`` instance, allowing you to retain it or cancel it later if necessary. public typealias DownloadTaskUpdatedBlock = ((_ newTask: DownloadTask?) -> Void) -/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache, -/// to provide a set of convenience methods to use Kingfisher for tasks. -/// You can use this class to retrieve an image via a specified URL from web or cache. +/// The main manager class of Kingfisher. It connects the Kingfisher downloader and cache to offer a set of convenient +/// methods for working with Kingfisher tasks. +/// +/// You can utilize this class to retrieve an image via a specified URL from the web or cache. public class KingfisherManager { /// Represents a shared manager used across Kingfisher. @@ -94,21 +111,26 @@ public class KingfisherManager { public static let shared = KingfisherManager() // Mark: Public Properties - /// The `ImageCache` used by this manager. It is `ImageCache.default` by default. - /// If a cache is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be - /// used instead. + + /// The ``ImageCache`` utilized by this manager, which defaults to ``ImageCache/default``. + /// + /// If a cache is specified in ``KingfisherManager/defaultOptions`` or ``KingfisherOptionsInfoItem/targetCache(_:)``, + /// those specified values will take precedence when Kingfisher attempts to retrieve or store images in the cache. public var cache: ImageCache - /// The `ImageDownloader` used by this manager. It is `ImageDownloader.default` by default. - /// If a downloader is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be - /// used instead. + /// The ``ImageDownloader`` utilized by this manager, which defaults to ``ImageDownloader/default``. + /// + /// If a downloader is specified in ``KingfisherManager/defaultOptions`` or ``KingfisherOptionsInfoItem/downloader(_:)``, + /// those specified values will take precedence when Kingfisher attempts to download the image data from a remote + /// server. public var downloader: ImageDownloader - /// Default options used by the manager. This option will be used in - /// Kingfisher manager related methods, as well as all view extension methods. - /// You can also passing other options for each image task by sending an `options` parameter - /// to Kingfisher's APIs. The per image options will overwrite the default ones, - /// if the option exists in both. + /// The default options used by the ``KingfisherManager`` instance. + /// + /// These options are utilized in Kingfisher manager-related methods, as well as all view extension methods. + /// You can also pass additional options for each image task by providing an `options` parameter to Kingfisher's APIs. + /// + /// Per-image options will override the default ones if there is a conflict. public var defaultOptions = KingfisherOptionsInfo.empty // Use `defaultOptions` to overwrite the `downloader` and `cache`. @@ -122,11 +144,12 @@ public class KingfisherManager { self.init(downloader: .default, cache: .default) } - /// Creates an image setting manager with specified downloader and cache. + /// Creates an image setting manager with the specified downloader and cache. /// /// - Parameters: - /// - downloader: The image downloader used to download images. - /// - cache: The image cache which stores memory and disk images. + /// - downloader: The image downloader used for image downloads. + /// - cache: The image cache that stores images in memory and on disk. + /// public init(downloader: ImageDownloader, cache: ImageCache) { self.downloader = downloader self.cache = cache @@ -137,26 +160,26 @@ public class KingfisherManager { // MARK: - Getting Images - /// Gets an image from a given resource. + /// Retrieves an image from a specified resource. + /// /// - Parameters: - /// - resource: The `Resource` object defines data information like key or URL. + /// - resource: The ``Resource`` object defining data information, such as a key or URL. /// - options: Options to use when creating the image. - /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an - /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in - /// main queue. - /// - downloadTaskUpdated: Called when a new image downloading task is created for current image retrieving. This - /// usually happens when an alternative source is used to replace the original (failed) - /// task. You can update your reference of `DownloadTask` if you want to manually `cancel` - /// the new task. - /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked - /// from the `options.callbackQueue`. If not specified, the main queue will be used. - /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource, - /// the started `DownloadTask` is returned. Otherwise, `nil` is returned. + /// - progressBlock: Called when the image download progress is updated. This block is invoked only if the response + /// contains an `expectedContentLength` and always runs on the main queue. + /// - downloadTaskUpdated: Called when a new image download task is created for the current image retrieval. This + /// typically occurs when an alternative source is used to replace the original (failed) task. You can update your + /// reference to the ``DownloadTask`` if you want to manually invoke ``DownloadTask/cancel()`` on the new task. + /// - completionHandler: Called when the image retrieval and setting are completed. This completion handler is + /// invoked from the `options.callbackQueue`. If not specified, the main queue is used. + /// + /// - Returns: A task representing the image download. If a download task is initiated for a ``Source/network(_:)`` resource, + /// the started ``DownloadTask`` is returned; otherwise, `nil` is returned. + /// + /// - Note: This method first checks whether the requested `resource` is already in the cache. If it is cached, + /// it returns `nil` and invokes the `completionHandler` after retrieving the cached image. Otherwise, it downloads + /// the `resource`, stores it in the cache, and then calls the `completionHandler`. /// - /// - Note: - /// This method will first check whether the requested `resource` is already in cache or not. If cached, - /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it - /// will download the `resource`, store it in cache, then call `completionHandler`. @discardableResult public func retrieveImage( with resource: Resource, @@ -174,27 +197,25 @@ public class KingfisherManager { ) } - /// Gets an image from a given resource. + /// Retrieves an image from a specified source. /// /// - Parameters: - /// - source: The `Source` object defines data information from network or a data provider. + /// - source: The ``Source`` object defining data information, such as a key or URL. /// - options: Options to use when creating the image. - /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an - /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in - /// main queue. - /// - downloadTaskUpdated: Called when a new image downloading task is created for current image retrieving. This - /// usually happens when an alternative source is used to replace the original (failed) - /// task. You can update your reference of `DownloadTask` if you want to manually `cancel` - /// the new task. - /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked - /// from the `options.callbackQueue`. If not specified, the main queue will be used. - /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource, - /// the started `DownloadTask` is returned. Otherwise, `nil` is returned. + /// - progressBlock: Called when the image download progress is updated. This block is invoked only if the response + /// contains an `expectedContentLength` and always runs on the main queue. + /// - downloadTaskUpdated: Called when a new image download task is created for the current image retrieval. This + /// typically occurs when an alternative source is used to replace the original (failed) task. You can update your + /// reference to the ``DownloadTask`` if you want to manually invoke ``DownloadTask/cancel()`` on the new task. + /// - completionHandler: Called when the image retrieval and setting are completed. This completion handler is + /// invoked from the `options.callbackQueue`. If not specified, the main queue is used. + /// + /// - Returns: A task representing the image download. If a download task is initiated for a ``Source/network(_:)`` resource, + /// the started ``DownloadTask`` is returned; otherwise, `nil` is returned. /// - /// - Note: - /// This method will first check whether the requested `source` is already in cache or not. If cached, - /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it - /// will try to load the `source`, store it in cache, then call `completionHandler`. + /// - Note: This method first checks whether the requested `source` is already in the cache. If it is cached, + /// it returns `nil` and invokes the `completionHandler` after retrieving the cached image. Otherwise, it downloads + /// the `source`, stores it in the cache, and then calls the `completionHandler`. /// @discardableResult public func retrieveImage( @@ -524,25 +545,25 @@ public class KingfisherManager { } } - /// Retrieves image from memory or disk cache. + /// Retrieves an image from either memory or disk cache. /// /// - Parameters: - /// - source: The target source from which to get image. - /// - key: The key to use when caching the image. - /// - url: Image request URL. This is not used when retrieving image from cache. It is just used for - /// `RetrieveImageResult` callback compatibility. - /// - options: Options on how to get the image from image cache. - /// - completionHandler: Called when the image retrieving finishes, either with succeeded - /// `RetrieveImageResult` or an error. - /// - Returns: `true` if the requested image or the original image before being processed is existing in cache. - /// Otherwise, this method returns `false`. + /// - source: The target source from which to retrieve the image. + /// - key: The key to use for caching the image. + /// - url: The image request URL. This is not used when retrieving an image from the cache; it is solely used for + /// compatibility with ``RetrieveImageResult`` callbacks. + /// - options: Options on how to retrieve the image from the image cache. + /// - completionHandler: Called when the image retrieval is complete, either with a successful + /// ``RetrieveImageResult`` or an error. + /// + /// - Returns: `true` if the requested image or the original image before processing exists in the cache. Otherwise, this method returns `false`. + /// + /// - Note: Image retrieval can occur in either the memory cache or the disk cache. The + /// ``KingfisherOptionsInfoItem/processor(_:)`` option in `options` is considered when searching the cache. If no + /// processed image is found, Kingfisher attempts to determine whether an original version of the image exists. If + /// an original exists, Kingfisher retrieves it from the cache and processes it. Subsequently, the processed image + /// is stored back in the cache for future use. /// - /// - Note: - /// The image retrieving could happen in either memory cache or disk cache. The `.processor` option in - /// `options` will be considered when searching in the cache. If no processed image is found, Kingfisher - /// will try to check whether an original version of that image is existing or not. If there is already an - /// original, Kingfisher retrieves it from cache and processes it. Then, the processed image will be store - /// back to cache for later use. func retrieveImageFromCache( source: Source, context: RetrievingContext, @@ -710,17 +731,22 @@ public class KingfisherManager { // Concurrency extension KingfisherManager { - /// Gets an image from a given resource. + + /// Retrieves an image from a specified resource. + /// /// - Parameters: - /// - resource: The `Resource` object defines data information like key or URL. + /// - resource: The ``Resource`` object defining data information, such as a key or URL. /// - options: Options to use when creating the image. - /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an - /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in - /// main queue. + /// - progressBlock: Called when the image download progress is updated. This block is invoked only if the response + /// contains an `expectedContentLength` and always runs on the main queue. + /// + /// - Returns: The ``RetrieveImageResult`` containing the retrieved image object and cache type. + /// - Throws: A ``KingfisherError`` if any issue occured during the image retrieving progress. + /// + /// - Note: This method first checks whether the requested `resource` is already in the cache. If it is cached, + /// it returns `nil` and invokes the `completionHandler` after retrieving the cached image. Otherwise, it downloads + /// the `resource`, stores it in the cache, and then calls the `completionHandler`. /// - /// - Note: This method will first check whether the requested `resource` is already in cache or not. If cached, - /// it returns the value after the cached image retrieved. Otherwise, it - /// will download the `resource`, store it in cache, then returns the value. public func retrieveImage( with resource: Resource, options: KingfisherOptionsInfo? = nil, @@ -734,18 +760,20 @@ extension KingfisherManager { ) } - /// Gets an image from a given resource. + /// Retrieves an image from a specified source. /// /// - Parameters: - /// - source: The `Source` object defines data information from network or a data provider. + /// - source: The ``Source`` object defining data information, such as a key or URL. /// - options: Options to use when creating the image. - /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an - /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in - /// main queue. + /// - progressBlock: Called when the image download progress is updated. This block is invoked only if the response + /// contains an `expectedContentLength` and always runs on the main queue. + /// + /// - Returns: The ``RetrieveImageResult`` containing the retrieved image object and cache type. + /// - Throws: A ``KingfisherError`` if any issue occured during the image retrieving progress. /// - /// - Note: This method will first check whether the requested `resource` is already in cache or not. If cached, - /// it returns the value after the cached image retrieved. Otherwise, it - /// will download the `resource`, store it in cache, then returns the value. + /// - Note: This method first checks whether the requested `source` is already in the cache. If it is cached, + /// it returns `nil` and invokes the `completionHandler` after retrieving the cached image. Otherwise, it downloads + /// the `source`, stores it in the cache, and then calls the `completionHandler`. /// public func retrieveImage( with source: Source, diff --git a/Sources/General/KingfisherOptionsInfo.swift b/Sources/General/KingfisherOptionsInfo.swift index 5f2aea63b..8866992bd 100644 --- a/Sources/General/KingfisherOptionsInfo.swift +++ b/Sources/General/KingfisherOptionsInfo.swift @@ -31,128 +31,163 @@ import UIKit #endif -/// KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. -/// You can use the enum of option item with value to control some behaviors of Kingfisher. +/// `KingfisherOptionsInfo` is a typealias for `[``KingfisherOptionsInfoItem``]`. +/// You can utilize the enum of option items with values to control certain behaviors of Kingfisher. public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem] extension Array where Element == KingfisherOptionsInfoItem { static let empty: KingfisherOptionsInfo = [] } -/// Represents the available option items could be used in `KingfisherOptionsInfo`. +/// Represents the available option items that can be used in ``KingfisherOptionsInfo``. public enum KingfisherOptionsInfoItem { - /// 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. + /// Kingfisher will utilize the associated ``ImageCache`` object when performing related operations, such as + /// attempting to retrieve cached images and storing downloaded images in it. case targetCache(ImageCache) - /// 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. + /// The ``ImageCache`` used for storing and retrieving original images. + /// + /// If ``originalCache(_:)`` is specified in the options, it will be given preference for storing and retrieving + /// original images. If there is no ``originalCache(_:)`` option, ``targetCache(_:)`` will be used to + /// store original images as well. + /// + /// When using ``KingfisherManager`` to download and store an image, if ``cacheOriginalImage`` is applied in the + /// options, the original image will be stored in the associated ``ImageCache`` of this option. + /// + /// Simultaneously, if a requested final image (with a processor applied) cannot be found in the ``targetCache(_:)``, + /// Kingfisher will attempt to search for the original image to see if it already exists. If found, it will be + /// utilized and processed with the given processor. This optimization prevents downloading the same image multiple + /// times. case originalCache(ImageCache) - /// Kingfisher will use the associated `ImageDownloader` object to download the requested images. + /// Kingfisher will utilize the associated ``ImageDownloader`` object to download the requested images. case downloader(ImageDownloader) - /// Member for animation transition when using `UIImageView`. Kingfisher will use the `ImageTransition` of - /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the - /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when - /// the image being retrieved from cache, set `.forceRefresh` as well. + /// This enum defines the transition effect to be applied when setting an image to an image view. + /// + /// Kingfisher uses the ``ImageTransition`` specified by this enum to animate the image in if it's downloaded from + /// the web. + /// + /// By default, the transition does not occur when the image is retrieved from either memory or disk cache. To + /// force the transition even when the image is retrieved from the cache, also set + /// ``KingfisherOptionsInfoItem/forceTransition``. case transition(ImageTransition) - /// Associated `Float` value will be set as the priority of image download task. The value for it should be - /// between 0.0~1.0. If this option not set, the default value (`URLSessionTask.defaultPriority`) will be used. + /// The associated `Float` value to be set as the priority of the image download task. + /// + /// This value should fall within the range of 0.0 to 1.0. If this option is not set, the default value + /// (`URLSessionTask.defaultPriority`) will be used. case downloadPriority(Float) - /// If set, Kingfisher will ignore the cache and try to start a download task for the image source. + /// When set, Kingfisher will disregard the cache and attempt to initiate a download task for the image source. case forceRefresh - /// If set, Kingfisher will try to retrieve the image from memory cache first. If the image is not in memory - /// cache, then it will ignore the disk cache but download the image again from network. 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. + /// Sets whether Kingfisher should try to load from memory cache first, and then perform a refresh from network. + /// + /// When set, Kingfisher will attempt to retrieve the image from memory cache first. If the image is not found in + /// the memory cache, it will skip the disk cache and download the image again from the network. This is useful + /// when you want to display a changeable image with the same URL within the same app session, while avoiding + /// multiple downloads. case fromMemoryCacheOrRefresh - /// If set, setting the image to an image view will happen with transition even when retrieved from cache. - /// See `.transition` option for more. + /// When set, applying a transition to set the image in an image view will occur even when the image is retrieved + /// from the cache. Refer to the ``transition(_:)`` option for more details. case forceTransition - /// If set, Kingfisher will only cache the value in memory but not in disk. + /// When set, Kingfisher will cache the value only in memory and not on disk. case cacheMemoryOnly - /// If set, Kingfisher will wait for caching operation to be completed before calling the completion block. + /// When set, Kingfisher will wait for the caching operation to be completed before invoking the completion block. case waitForCache - /// If set, Kingfisher will 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. + /// When set, Kingfisher will attempt to retrieve the image solely from the cache and not from the network. + /// + /// If the image is not found in the cache, the image retrieval will fail with a + /// ``KingfisherError/CacheErrorReason/imageNotExisting(key:)`` error. case onlyFromCache - /// Decode the image in background thread before using. It 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 to - /// prepare the image for using. + /// Decode the image on a background thread before usage. + /// + /// This process involves decoding the downloaded image data and performing off-screen rendering to extract pixel + /// information in the background. While this can accelerate display performance, it may require additional time + /// to prepare the image for use. case backgroundDecode /// The associated value will be used as the target queue of dispatch callbacks when retrieving images from /// cache. If not set, Kingfisher will use `.mainCurrentOrAsync` for callbacks. /// - /// - Note: - /// This option does not affect the callbacks for UI related extension methods. You will always get the + /// - Note: This option does not affect the callbacks for UI related extension methods. You will always get the /// callbacks called from main queue. + + /// The associated value will serve as the target queue for dispatch callbacks when retrieving images from the cache. + /// + /// If not set, Kingfisher will use ``CallbackQueue/mainCurrentOrAsync`` for callbacks. + /// + /// - Note: This option does not impact the callbacks for UI-related extension methods. Those callbacks will always + /// occur on the main queue. case callbackQueue(CallbackQueue) - /// The associated value will be used as the scale factor 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. + /// The associated value will be used as the scale factor when converting retrieved image data to an image object. + /// + /// Specify the image scale rather than your screen scale. You should set the correct scale when dealing with 2x or + /// 3x retina images. Otherwise, Kingfisher will convert the data to an image object with a scale of 1.0. case scaleFactor(CGFloat) - /// Whether all the animated image data should be preloaded. Default is `false`, which means only following frames - /// will be loaded on need. If `true`, all the animated image data will be loaded and decoded into memory. - /// - /// This option is mainly used for back compatibility internally. You should not set it directly. Instead, - /// you should choose the image view class to control the GIF data loading. There are two classes in Kingfisher - /// support to display a GIF image. `AnimatedImageView` does not preload all data, it takes much less memory, but - /// uses more CPU when display. While a normal image view (`UIImageView` or `NSImageView`) loads all data at once, - /// which uses more memory but only decode image frames once. + /// Determines whether all the animated image data should be preloaded. + /// + /// The default value is `false`, which means only the following frames will be loaded on demand. If set to `true`, + /// all the animated image data will be loaded and decoded into memory. + /// + /// This option is primarily used for internal backward compatibility. It should not be set directly. Instead, you + /// should choose the appropriate image view class to control the GIF data loading. Kingfisher offers two classes + /// for displaying GIF images: ``AnimatedImageView``, which does not preload all data, consumes less memory, but uses + /// more CPU during display; and a regular image view (`UIImageView` or `NSImageView`), which loads all data at + /// once, consumes more memory, but decodes image frames only once. case preloadAllAnimationData - /// The `ImageDownloadRequestModifier` contained will be used to change the 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. - /// The original request will be sent without any modification by default. + /// The contained ``ImageDownloadRequestModifier`` will be used to alter the request before it is sent. + /// + /// This is the final opportunity to modify the image download request. You can customize the request for various + /// purposes, such as adding an authentication token to the header, performing basic HTTP authentication, or URL + /// mapping. + /// + /// By default, the original request is sent without any modifications. case requestModifier(AsyncImageDownloadRequestModifier) - /// The `ImageDownloadRedirectHandler` contained 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. + /// The contained ``ImageDownloadRedirectHandler`` will be used to alter the request during redirection. + /// + /// This provides an opportunity to customize the image download request during redirection. You can modify the + /// request for various purposes, such as adding an authentication token to the header, performing basic HTTP + /// authentication, or URL mapping. + /// + /// By default, the original redirection request is sent without any modifications. case redirectHandler(ImageDownloadRedirectHandler) - /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image - /// and/or apply some filter on it. If a cache is connected to the downloader (it happens when you are using - /// KingfisherManager or any of the view extension methods), the converted image will also be sent to cache as well. - /// If not set, the `DefaultImageProcessor.default` will be used. + /// The processor used in the image retrieval task. + /// + /// After downloading is complete, a processor will convert the downloaded data into an image and/or apply various + /// filters or transformations to it. + /// + /// If a cache is linked to the downloader (which occurs when you use ``KingfisherManager`` or any of the view + /// extension methods), the converted image will also be stored in the cache. If not set, the + /// ``DefaultImageProcessor/default`` will be used. case processor(ImageProcessor) - /// Provides a `CacheSerializer` to convert some data to an image object for - /// retrieving from disk cache or vice versa for storing to disk cache. - /// If not set, the `DefaultCacheSerializer.default` will be used. + /// Offers a ``CacheSerializer`` to convert data into an image object for retrieval from disk cache, or vice versa + /// for storage in the disk cache. + /// + /// If not set, the ``DefaultCacheSerializer/default`` will be used. case cacheSerializer(CacheSerializer) - /// An `ImageModifier` is for modifying an image as needed right before it is used. 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`. + /// An ``ImageModifier`` for making adjustments to an image right before it is used. + /// + /// If the image was directly fetched from the downloader, the modifier will be applied immediately after the + /// ``ImageProcessor``. If the image is retrieved from a cache, the modifier will be applied after the + /// ``CacheSerializer``. /// - /// Use `ImageModifier` when you need to set properties that do not persist when caching the image on a concrete - /// type of `Image`, such as the `renderingMode` or the `alignmentInsets` of `UIImage`. + /// Use the ``ImageModifier`` when you need to set properties that do not persist when caching the image with a + /// specific image type. Examples include setting the `renderingMode` or `alignmentInsets` of a `UIImage`. case imageModifier(ImageModifier) /// Keep the existing image of image view while setting another image to it. @@ -160,78 +195,108 @@ public enum KingfisherOptionsInfoItem { /// will be ignored and the current image will be kept while loading or downloading the new image. case keepCurrentImageWhileLoading - /// If set, Kingfisher will only load the first frame from an animated image file as a single image. - /// Loading an animated images may take too much memory. It will be useful when you want to display a - /// static preview of the first frame from an animated image. + /// When set, Kingfisher will load only the first frame from an animated image file as a single image. /// - /// This option will be ignored if the target image is not animated image data. + /// Loading animated images can consume a significant amount of memory. This option is useful when you want to + /// display a static preview of the first frame from an animated image. It will be ignored if the target image is + /// not animated image data. case onlyLoadFirstFrame - /// 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. + /// When set and an non-default ``ImageProcessor`` is used, Kingfisher will attempt to cache both the final result + /// and the original image. + /// + /// Kingfisher will have the opportunity to use the original image when another processor is applied to the same + /// resource, instead of downloading it anew. You can use ``KingfisherOptionsInfoItem/originalCache(_:)`` to + /// specify a cache for the original images if necessary. /// - /// The original image will be only cached to disk storage. + /// The original image will only be cached to disk storage. case cacheOriginalImage - /// If set and an image retrieving error occurred Kingfisher will set provided image (or empty) - /// in place of requested one. It's useful when you don't want to show placeholder - /// during loading time but wants to use some default image when requests will be failed. + /// When set and an image retrieval error occurs, Kingfisher will replace the requested image with the provided + /// image (or an empty image). + /// + /// This is useful when you prefer not to display a placeholder during loading but want to use a default image when + /// requests fail. case onFailureImage(KFCrossPlatformImage?) - /// If set and used in `ImagePrefetcher`, the prefetching operation will load the images into memory storage - /// aggressively. By default this is not contained in the options, that means if the requested image is already - /// in disk cache, Kingfisher will not try to load it to memory. + /// When set and used in methods of ``ImagePrefetcher``, the prefetching operation will aggressively load the images + /// into memory storage. + /// + /// By default, this option is not included in the options. This means that if the requested image is already in + /// the disk cache, Kingfisher will not attempt to load it into memory. case alsoPrefetchToMemory - /// If set, the disk storage loading will 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. + /// When set, disk storage loading will occur in the same calling queue. /// - /// 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. + /// By default, disk storage file loading operates on its own queue with asynchronous dispatch behavior. While this + /// provides improved non-blocking disk loading performance, it can lead to flickering when you reload an image from + /// disk if the image view already has an image set. + /// + /// Setting this option will eliminate 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). However, this comes with a tradeoff in + /// loading performance. case loadDiskFileSynchronously - /// Options to control the writing of data to disk storage - /// If set, options will be passed the store operation for a new files. + /// Options for controlling the data writing process to disk storage. + /// + /// When set, these options will be passed to the store operation for new files. case diskStoreWriteOptions(Data.WritingOptions) - /// The expiration setting for memory cache. By default, the underlying `MemoryStorage.Backend` uses the - /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this associated - /// value to overwrite the config setting for this caching item. + /// When set, use the associated ``StorageExpiration`` value for the memory cache to determine the expiration date. + /// + /// By default, the underlying ``MemoryStorage/Backend`` uses the expiration defined in its ``MemoryStorage/Config`` + /// for all items. If this option is set, the ``MemoryStorage/Backend`` will utilize the associated value to + /// override the configuration setting for this caching item. case memoryCacheExpiration(StorageExpiration) - /// 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. + /// When set, use the associated ``ExpirationExtending`` value for the memory cache to determine the extending policy + /// when setting the next expiration date. + /// + /// The item's expiration date will be extended after access to keep the "most recently accessed" items alive for a + /// longer duration in the cache. + /// + /// By default, the underlying ``MemoryStorage/Backend`` uses the initial cache expiration as the extending value, + /// which is ``ExpirationExtending/cacheTime``. /// - /// To disable extending option at all add memoryCacheAccessExtendingExpiration(.none) to options. + /// - Note: To disable expiration extending entirely, use ``ExpirationExtending/none``. case memoryCacheAccessExtendingExpiration(ExpirationExtending) - /// The expiration setting for disk cache. By default, the underlying `DiskStorage.Backend` uses the - /// expiration in its config for all items. If set, the `DiskStorage.Backend` will use this associated - /// value to overwrite the config setting for this caching item. + /// When set, use the associated ``StorageExpiration`` value for the disk cache to determine the expiration date. + /// + /// By default, the underlying ``DiskStorage/Backend`` uses the expiration defined in its ``DiskStorage/Config`` + /// for all items. If this option is set, the ``DiskStorage/Backend`` will utilize the associated value to override + /// the configuration setting for this caching item. case diskCacheExpiration(StorageExpiration) - /// 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 add diskCacheAccessExtendingExpiration(.none) to options. + /// When set, use the associated ``ExpirationExtending`` value for the disk cache to determine the extending policy + /// when setting the next expiration date. + /// + /// The item's expiration date will be extended after access to keep the "most recently accessed" items alive for a + /// longer duration in the cache. + /// + /// By default, the underlying ``DiskStorage/Backend`` uses the initial cache expiration as the extending value, + /// which is ``ExpirationExtending/cacheTime``. + /// + /// - Note: To disable expiration extending entirely, use ``ExpirationExtending/none``. case diskCacheAccessExtendingExpiration(ExpirationExtending) - /// Decides on which queue 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). + /// Determines the queue on which image processing should occur. + /// + /// By default, Kingfisher uses an internal pre-defined serial queue to process images. Use this option to modify + /// this behavior. For instance, you can specify ``CallbackQueue/mainCurrentOrAsync`` to process the image on the + /// main queue, preventing potential flickering (but with the risk of blocking the UI, especially if the processor + /// is time-consuming). case processingQueue(CallbackQueue) - /// Enable progressive image loading, Kingfisher will use the associated `ImageProgressive` value to process the - /// progressive JPEG data and display it in a progressive way. + /// Enables progressive image loading. + /// + /// Kingfisher will use the associated ``ImageProgressive`` value to process progressive JPEG data and display + /// it progressively, if the image supports it. case progressiveJPEG(ImageProgressive) - /// The alternative sources will be used when the original input `Source` fails. The `Source`s in the associated + /// Sets a set of alternative sources when the original input `Source` fails to load. + /// + /// The `Source`s in the associated /// 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 `[Source]`s are used but /// the loading is still failing, an `imageSettingError` with `alternativeSourcesExhausted` as its reason will be @@ -240,35 +305,60 @@ public enum KingfisherOptionsInfoItem { /// This option is useful if you want to implement a fallback solution for setting image. /// /// User cancellation will not trigger the alternative source loading. + /// + + /// Specifies a set of alternative sources to use when the original input ``Source`` fails to load. + /// + /// The ``Source``s in the associated 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 halt as soon as a source is loaded successfully. + /// If all ``Source``s are used, but loading still fails, a + /// ``KingfisherError/ImageSettingErrorReason/alternativeSourcesExhausted(_:)``will be used as the error in the + /// result. + /// + /// This option is useful for implementing a fallback solution for image setting. + /// + /// - Note: User cancellation will not trigger the loading of alternative sources. case alternativeSources([Source]) - /// Provide a retry strategy which will be used when something gets wrong during the image retrieving process from - /// `KingfisherManager`. You can define a strategy by create a type conforming to the `RetryStrategy` protocol. + /// Provides a retry strategy to use when something goes wrong during the image retrieval process from + /// ``KingfisherManager``. /// - /// - Note: - /// - /// All extension methods of Kingfisher (`kf` extensions on `UIImageView` or `UIButton`) retrieve images through - /// `KingfisherManager`, so the retry strategy also applies when using them. However, this option does not apply - /// when pass to an `ImageDownloader` or `ImageCache`. + /// You can define a strategy by creating a type that conforms to the ``RetryStrategy`` protocol. When Kingfisher + /// encounters a loading failure, it follows the defined retry strategy and retries until a ``RetryDecision/stop`` + /// is received. /// + /// - Note: All extension methods of Kingfisher (the `kf` extensions on `UIImageView` or `UIButton`, for example) + /// retrieve images through ``KingfisherManager``, so the retry strategy also applies when using them. However, + /// this option does not apply when passed to an ``ImageDownloader`` or an ``ImageCache`` directly. case retryStrategy(RetryStrategy) - /// 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. + /// Specifies the `Source` to load when the user enables Low Data Mode and the original source fails due to the data + /// constraint. + /// + /// When the user enables Low Data Mode in the system settings, and the original source fails with an + /// `NSURLErrorNetworkUnavailableReason.constrained` error, Kingfisher uses this source instead to load an image + /// for Low Data Mode. + /// + /// When this option is set, the `allowsConstrainedNetworkAccess` property of the request for the original source + /// will be set to `false`, and the ``Source`` in the associated value will be used to retrieve the image for Low + /// Data Mode. Typically, you can provide a low-resolution version of your image or a local image provider to + /// display a placeholder to save data usage. + /// + /// If not set or if the associated optional ``Source`` value is `nil`, the device's Low Data Mode will be ignored, + /// and the original source will be loaded following the system default behavior. case lowDataMode(Source?) } +// MARK: - KingfisherParsedOptionsInfo + // Improve performance by parsing the input `KingfisherOptionsInfo` (self) first. // So we can prevent the iterating over the options array again and again. -/// The parsed options info used across Kingfisher methods. Each property in this type corresponds a case member -/// in `KingfisherOptionsInfoItem`. When a `KingfisherOptionsInfo` sent to Kingfisher related methods, it will be -/// parsed and converted to a `KingfisherParsedOptionsInfo` first, and pass through the internal methods. + +/// Represents the parsed options info used throughout Kingfisher methods. +/// +/// Each property in this type corresponds to a case member in ``KingfisherOptionsInfoItem``. When a +/// ``KingfisherOptionsInfo`` is sent to Kingfisher-related methods, it will be parsed and converted to a +/// ``KingfisherParsedOptionsInfo`` first before passing through the internal methods. public struct KingfisherParsedOptionsInfo { public var targetCache: ImageCache? = nil