KingfisherOptionsInfo.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. //
  2. // KingfisherOptionsInfo.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/23.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. #if os(macOS)
  27. import AppKit
  28. #else
  29. import UIKit
  30. #endif
  31. /// KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem].
  32. /// You can use the enum of option item with value to control some behaviors of Kingfisher.
  33. public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem]
  34. extension Array where Element == KingfisherOptionsInfoItem {
  35. static let empty: KingfisherOptionsInfo = []
  36. }
  37. /// Represents the available option items could be used in `KingfisherOptionsInfo`.
  38. public enum KingfisherOptionsInfoItem {
  39. /// Kingfisher will use the associated `ImageCache` object when handling related operations,
  40. /// including trying to retrieve the cached images and store the downloaded image to it.
  41. case targetCache(ImageCache)
  42. /// The `ImageCache` for storing and retrieving original images. If `originalCache` is
  43. /// contained in the options, it will be preferred for storing and retrieving original images.
  44. /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images.
  45. ///
  46. /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is
  47. /// applied in the option, the original image will be stored to this `originalCache`. At the
  48. /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`,
  49. /// Kingfisher will try to search the original image to check whether it is already there. If found,
  50. /// it will be used and applied with the given processor. It is an optimization for not downloading
  51. /// the same image for multiple times.
  52. case originalCache(ImageCache)
  53. /// Kingfisher will use the associated `ImageDownloader` object to download the requested images.
  54. case downloader(ImageDownloader)
  55. /// Member for animation transition when using `UIImageView`. Kingfisher will use the `ImageTransition` of
  56. /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the
  57. /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when
  58. /// the image being retrieved from cache, set `.forceRefresh` as well.
  59. case transition(ImageTransition)
  60. /// Associated `Float` value will be set as the priority of image download task. The value for it should be
  61. /// between 0.0~1.0. If this option not set, the default value (`URLSessionTask.defaultPriority`) will be used.
  62. case downloadPriority(Float)
  63. /// If set, Kingfisher will ignore the cache and try to start a download task for the image source.
  64. case forceRefresh
  65. /// If set, Kingfisher will try to retrieve the image from memory cache first. If the image is not in memory
  66. /// cache, then it will ignore the disk cache but download the image again from network. This is useful when
  67. /// you want to display a changeable image behind the same url at the same app session, while avoiding download
  68. /// it for multiple times.
  69. case fromMemoryCacheOrRefresh
  70. /// If set, setting the image to an image view will happen with transition even when retrieved from cache.
  71. /// See `.transition` option for more.
  72. case forceTransition
  73. /// If set, Kingfisher will only cache the value in memory but not in disk.
  74. case cacheMemoryOnly
  75. /// If set, Kingfisher will wait for caching operation to be completed before calling the completion block.
  76. case waitForCache
  77. /// If set, Kingfisher will only try to retrieve the image from cache, but not from network. If the image is not in
  78. /// cache, the image retrieving will fail with the `KingfisherError.cacheError` with `.imageNotExisting` as its
  79. /// reason.
  80. case onlyFromCache
  81. /// Decode the image in background thread before using. It will decode the downloaded image data and do a off-screen
  82. /// rendering to extract pixel information in background. This can speed up display, but will cost more time to
  83. /// prepare the image for using.
  84. case backgroundDecode
  85. /// The associated value will be used as the target queue of dispatch callbacks when retrieving images from
  86. /// cache. If not set, Kingfisher will use `.mainCurrentOrAsync` for callbacks.
  87. ///
  88. /// - Note:
  89. /// This option does not affect the callbacks for UI related extension methods. You will always get the
  90. /// callbacks called from main queue.
  91. case callbackQueue(CallbackQueue)
  92. /// The associated value will be used as the scale factor when converting retrieved data to an image.
  93. /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing
  94. /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0.
  95. case scaleFactor(CGFloat)
  96. /// Whether all the animated image data should be preloaded. Default is `false`, which means only following frames
  97. /// will be loaded on need. If `true`, all the animated image data will be loaded and decoded into memory.
  98. ///
  99. /// This option is mainly used for back compatibility internally. You should not set it directly. Instead,
  100. /// you should choose the image view class to control the GIF data loading. There are two classes in Kingfisher
  101. /// support to display a GIF image. `AnimatedImageView` does not preload all data, it takes much less memory, but
  102. /// uses more CPU when display. While a normal image view (`UIImageView` or `NSImageView`) loads all data at once,
  103. /// which uses more memory but only decode image frames once.
  104. case preloadAllAnimationData
  105. /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent.
  106. /// This is the last chance you can modify the image download request. You can modify the request for some
  107. /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping.
  108. /// The original request will be sent without any modification by default.
  109. case requestModifier(AsyncImageDownloadRequestModifier)
  110. /// The `ImageDownloadRedirectHandler` contained will be used to change the request before redirection.
  111. /// This is the possibility you can modify the image download request during redirect. You can modify the request for
  112. /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url
  113. /// mapping.
  114. /// The original redirection request will be sent without any modification by default.
  115. case redirectHandler(ImageDownloadRedirectHandler)
  116. /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image
  117. /// and/or apply some filter on it. If a cache is connected to the downloader (it happens when you are using
  118. /// KingfisherManager or any of the view extension methods), the converted image will also be sent to cache as well.
  119. /// If not set, the `DefaultImageProcessor.default` will be used.
  120. case processor(ImageProcessor)
  121. /// Provides a `CacheSerializer` to convert some data to an image object for
  122. /// retrieving from disk cache or vice versa for storing to disk cache.
  123. /// If not set, the `DefaultCacheSerializer.default` will be used.
  124. case cacheSerializer(CacheSerializer)
  125. /// An `ImageModifier` is for modifying an image as needed right before it is used. If the image was fetched
  126. /// directly from the downloader, the modifier will run directly after the `ImageProcessor`. If the image is being
  127. /// fetched from a cache, the modifier will run after the `CacheSerializer`.
  128. ///
  129. /// Use `ImageModifier` when you need to set properties that do not persist when caching the image on a concrete
  130. /// type of `Image`, such as the `renderingMode` or the `alignmentInsets` of `UIImage`.
  131. case imageModifier(ImageModifier)
  132. /// Keep the existing image of image view while setting another image to it.
  133. /// By setting this option, the placeholder image parameter of image view extension method
  134. /// will be ignored and the current image will be kept while loading or downloading the new image.
  135. case keepCurrentImageWhileLoading
  136. /// If set, Kingfisher will only load the first frame from an animated image file as a single image.
  137. /// Loading an animated images may take too much memory. It will be useful when you want to display a
  138. /// static preview of the first frame from an animated image.
  139. ///
  140. /// This option will be ignored if the target image is not animated image data.
  141. case onlyLoadFirstFrame
  142. /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original
  143. /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same
  144. /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original
  145. /// images if necessary.
  146. ///
  147. /// The original image will be only cached to disk storage.
  148. case cacheOriginalImage
  149. /// If set and an image retrieving error occurred Kingfisher will set provided image (or empty)
  150. /// in place of requested one. It's useful when you don't want to show placeholder
  151. /// during loading time but wants to use some default image when requests will be failed.
  152. case onFailureImage(KFCrossPlatformImage?)
  153. /// If set and used in `ImagePrefetcher`, the prefetching operation will load the images into memory storage
  154. /// aggressively. By default this is not contained in the options, that means if the requested image is already
  155. /// in disk cache, Kingfisher will not try to load it to memory.
  156. case alsoPrefetchToMemory
  157. /// If set, the disk storage loading will happen in the same calling queue. By default, disk storage file loading
  158. /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk
  159. /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already
  160. /// has an image set.
  161. ///
  162. /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue
  163. /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance.
  164. case loadDiskFileSynchronously
  165. /// Options to control the writing of data to disk storage
  166. /// If set, options will be passed the store operation for a new files.
  167. case diskStoreWriteOptions(Data.WritingOptions)
  168. /// The expiration setting for memory cache. By default, the underlying `MemoryStorage.Backend` uses the
  169. /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this associated
  170. /// value to overwrite the config setting for this caching item.
  171. case memoryCacheExpiration(StorageExpiration)
  172. /// The expiration extending setting for memory cache. The item expiration time will be incremented by this
  173. /// value after access.
  174. /// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending
  175. /// value: .cacheTime.
  176. ///
  177. /// To disable extending option at all add memoryCacheAccessExtendingExpiration(.none) to options.
  178. case memoryCacheAccessExtendingExpiration(ExpirationExtending)
  179. /// The expiration setting for disk cache. By default, the underlying `DiskStorage.Backend` uses the
  180. /// expiration in its config for all items. If set, the `DiskStorage.Backend` will use this associated
  181. /// value to overwrite the config setting for this caching item.
  182. case diskCacheExpiration(StorageExpiration)
  183. /// The expiration extending setting for disk cache. The item expiration time will be incremented by this value after access.
  184. /// By default, the underlying `DiskStorage.Backend` uses the initial cache expiration as extending value: .cacheTime.
  185. /// To disable extending option at all add diskCacheAccessExtendingExpiration(.none) to options.
  186. case diskCacheAccessExtendingExpiration(ExpirationExtending)
  187. /// Decides on which queue the image processing should happen. By default, Kingfisher uses a pre-defined serial
  188. /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync`
  189. /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of
  190. /// blocking the UI, especially if the processor needs a lot of time to run).
  191. case processingQueue(CallbackQueue)
  192. /// Enable progressive image loading, Kingfisher will use the associated `ImageProgressive` value to process the
  193. /// progressive JPEG data and display it in a progressive way.
  194. case progressiveJPEG(ImageProgressive)
  195. /// The alternative sources will be used when the original input `Source` fails. The `Source`s in the associated
  196. /// array will be used to start a new image loading task if the previous task fails due to an error. The image
  197. /// source loading process will stop as soon as a source is loaded successfully. If all `[Source]`s are used but
  198. /// the loading is still failing, an `imageSettingError` with `alternativeSourcesExhausted` as its reason will be
  199. /// thrown out.
  200. ///
  201. /// This option is useful if you want to implement a fallback solution for setting image.
  202. ///
  203. /// User cancellation will not trigger the alternative source loading.
  204. case alternativeSources([Source])
  205. /// Provide a retry strategy which will be used when something gets wrong during the image retrieving process from
  206. /// `KingfisherManager`. You can define a strategy by create a type conforming to the `RetryStrategy` protocol.
  207. ///
  208. /// - Note:
  209. ///
  210. /// All extension methods of Kingfisher (`kf` extensions on `UIImageView` or `UIButton`) retrieve images through
  211. /// `KingfisherManager`, so the retry strategy also applies when using them. However, this option does not apply
  212. /// when pass to an `ImageDownloader` or `ImageCache`.
  213. ///
  214. case retryStrategy(RetryStrategy)
  215. /// The `Source` should be loaded when user enables Low Data Mode and the original source fails with an
  216. /// `NSURLErrorNetworkUnavailableReason.constrained` error. When this option is set, the
  217. /// `allowsConstrainedNetworkAccess` property of the request for the original source will be set to `false` and the
  218. /// `Source` in associated value will be used to retrieve the image for low data mode. Usually, you can provide a
  219. /// low-resolution version of your image or a local image provider to display a placeholder.
  220. ///
  221. /// If not set or the `source` is `nil`, the device Low Data Mode will be ignored and the original source will
  222. /// be loaded following the system default behavior, in a normal way.
  223. case lowDataMode(Source?)
  224. }
  225. // Improve performance by parsing the input `KingfisherOptionsInfo` (self) first.
  226. // So we can prevent the iterating over the options array again and again.
  227. /// The parsed options info used across Kingfisher methods. Each property in this type corresponds a case member
  228. /// in `KingfisherOptionsInfoItem`. When a `KingfisherOptionsInfo` sent to Kingfisher related methods, it will be
  229. /// parsed and converted to a `KingfisherParsedOptionsInfo` first, and pass through the internal methods.
  230. public struct KingfisherParsedOptionsInfo {
  231. public var targetCache: ImageCache? = nil
  232. public var originalCache: ImageCache? = nil
  233. public var downloader: ImageDownloader? = nil
  234. public var transition: ImageTransition = .none
  235. public var downloadPriority: Float = URLSessionTask.defaultPriority
  236. public var forceRefresh = false
  237. public var fromMemoryCacheOrRefresh = false
  238. public var forceTransition = false
  239. public var cacheMemoryOnly = false
  240. public var waitForCache = false
  241. public var onlyFromCache = false
  242. public var backgroundDecode = false
  243. public var preloadAllAnimationData = false
  244. public var callbackQueue: CallbackQueue = .mainCurrentOrAsync
  245. public var scaleFactor: CGFloat = 1.0
  246. public var requestModifier: AsyncImageDownloadRequestModifier? = nil
  247. public var redirectHandler: ImageDownloadRedirectHandler? = nil
  248. public var processor: ImageProcessor = DefaultImageProcessor.default
  249. public var imageModifier: ImageModifier? = nil
  250. public var cacheSerializer: CacheSerializer = DefaultCacheSerializer.default
  251. public var keepCurrentImageWhileLoading = false
  252. public var onlyLoadFirstFrame = false
  253. public var cacheOriginalImage = false
  254. public var onFailureImage: Optional<KFCrossPlatformImage?> = .none
  255. public var alsoPrefetchToMemory = false
  256. public var loadDiskFileSynchronously = false
  257. public var diskStoreWriteOptions: Data.WritingOptions = []
  258. public var memoryCacheExpiration: StorageExpiration? = nil
  259. public var memoryCacheAccessExtendingExpiration: ExpirationExtending = .cacheTime
  260. public var diskCacheExpiration: StorageExpiration? = nil
  261. public var diskCacheAccessExtendingExpiration: ExpirationExtending = .cacheTime
  262. public var processingQueue: CallbackQueue? = nil
  263. public var progressiveJPEG: ImageProgressive? = nil
  264. public var alternativeSources: [Source]? = nil
  265. public var retryStrategy: RetryStrategy? = nil
  266. public var lowDataModeSource: Source? = nil
  267. var onDataReceived: [DataReceivingSideEffect]? = nil
  268. public init(_ info: KingfisherOptionsInfo?) {
  269. guard let info = info else { return }
  270. for option in info {
  271. switch option {
  272. case .targetCache(let value): targetCache = value
  273. case .originalCache(let value): originalCache = value
  274. case .downloader(let value): downloader = value
  275. case .transition(let value): transition = value
  276. case .downloadPriority(let value): downloadPriority = value
  277. case .forceRefresh: forceRefresh = true
  278. case .fromMemoryCacheOrRefresh: fromMemoryCacheOrRefresh = true
  279. case .forceTransition: forceTransition = true
  280. case .cacheMemoryOnly: cacheMemoryOnly = true
  281. case .waitForCache: waitForCache = true
  282. case .onlyFromCache: onlyFromCache = true
  283. case .backgroundDecode: backgroundDecode = true
  284. case .preloadAllAnimationData: preloadAllAnimationData = true
  285. case .callbackQueue(let value): callbackQueue = value
  286. case .scaleFactor(let value): scaleFactor = value
  287. case .requestModifier(let value): requestModifier = value
  288. case .redirectHandler(let value): redirectHandler = value
  289. case .processor(let value): processor = value
  290. case .imageModifier(let value): imageModifier = value
  291. case .cacheSerializer(let value): cacheSerializer = value
  292. case .keepCurrentImageWhileLoading: keepCurrentImageWhileLoading = true
  293. case .onlyLoadFirstFrame: onlyLoadFirstFrame = true
  294. case .cacheOriginalImage: cacheOriginalImage = true
  295. case .onFailureImage(let value): onFailureImage = .some(value)
  296. case .alsoPrefetchToMemory: alsoPrefetchToMemory = true
  297. case .loadDiskFileSynchronously: loadDiskFileSynchronously = true
  298. case .diskStoreWriteOptions(let options): diskStoreWriteOptions = options
  299. case .memoryCacheExpiration(let expiration): memoryCacheExpiration = expiration
  300. case .memoryCacheAccessExtendingExpiration(let expirationExtending): memoryCacheAccessExtendingExpiration = expirationExtending
  301. case .diskCacheExpiration(let expiration): diskCacheExpiration = expiration
  302. case .diskCacheAccessExtendingExpiration(let expirationExtending): diskCacheAccessExtendingExpiration = expirationExtending
  303. case .processingQueue(let queue): processingQueue = queue
  304. case .progressiveJPEG(let value): progressiveJPEG = value
  305. case .alternativeSources(let sources): alternativeSources = sources
  306. case .retryStrategy(let strategy): retryStrategy = strategy
  307. case .lowDataMode(let source): lowDataModeSource = source
  308. }
  309. }
  310. if originalCache == nil {
  311. originalCache = targetCache
  312. }
  313. }
  314. }
  315. extension KingfisherParsedOptionsInfo {
  316. var imageCreatingOptions: ImageCreatingOptions {
  317. return ImageCreatingOptions(
  318. scale: scaleFactor,
  319. duration: 0.0,
  320. preloadAll: preloadAllAnimationData,
  321. onlyFirstFrame: onlyLoadFirstFrame)
  322. }
  323. }
  324. protocol DataReceivingSideEffect: AnyObject {
  325. var onShouldApply: () -> Bool { get set }
  326. func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data)
  327. }
  328. class ImageLoadingProgressSideEffect: DataReceivingSideEffect {
  329. var onShouldApply: () -> Bool = { return true }
  330. let block: DownloadProgressBlock
  331. init(_ block: @escaping DownloadProgressBlock) {
  332. self.block = block
  333. }
  334. func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) {
  335. guard self.onShouldApply() else { return }
  336. guard let expectedContentLength = task.task.response?.expectedContentLength,
  337. expectedContentLength != -1 else
  338. {
  339. return
  340. }
  341. let dataLength = Int64(task.mutableData.count)
  342. DispatchQueue.main.async {
  343. self.block(dataLength, expectedContentLength)
  344. }
  345. }
  346. }