ImageCache.swift 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. //
  2. // ImageCache.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  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. extension Notification.Name {
  32. /// This notification is sent when the disk cache is cleared, either due to expired cached files or the total size
  33. /// exceeding the maximum allowed size.
  34. ///
  35. /// The `object` of this notification is the ``ImageCache`` object that sends the notification. You can retrieve a
  36. /// list of removed hashes (files) by accessing the array under the ``KingfisherDiskCacheCleanedHashKey`` key in
  37. /// the `userInfo` of the received notification object. By checking the array, you can determine the hash codes
  38. /// of the removed files.
  39. ///
  40. /// > Invoking the `clearDiskCache` method manually will not trigger this notification.
  41. public static let KingfisherDidCleanDiskCache =
  42. Notification.Name("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache")
  43. }
  44. /// Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCache` notification.
  45. public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash"
  46. /// The type of cache for a cached image.
  47. public enum CacheType: Sendable {
  48. /// The image is not yet cached when retrieving it.
  49. ///
  50. /// This indicates that the image was recently downloaded or generated rather than being retrieved from either
  51. /// memory or disk cache.
  52. case none
  53. /// The image is cached in memory and retrieved from there.
  54. case memory
  55. /// The image is cached in disk and retrieved from there.
  56. case disk
  57. /// Indicates whether the cache type represents the image is already cached or not.
  58. public var cached: Bool {
  59. switch self {
  60. case .memory, .disk: return true
  61. case .none: return false
  62. }
  63. }
  64. }
  65. /// Represents the result of the caching operation.
  66. public struct CacheStoreResult: Sendable {
  67. /// The caching result for memory cache.
  68. ///
  69. /// Caching an image to memory will never fail.
  70. public let memoryCacheResult: Result<(), Never>
  71. /// The caching result for disk cache.
  72. ///
  73. /// If an error occurs during the caching operation, you can retrieve it from the `.failure` case of this value.
  74. /// Usually, the error contains a ``KingfisherError/CacheErrorReason``.
  75. public let diskCacheResult: Result<(), KingfisherError>
  76. }
  77. extension KFCrossPlatformImage: CacheCostCalculable {
  78. /// The cost of an image.
  79. ///
  80. /// It is an estimated size represented as a bitmap, measured in bytes of all pixels. A larger cost indicates that
  81. /// when cached in memory, it occupies more memory space. This cost contributes to the
  82. /// ``MemoryStorage/Config/countLimit``.
  83. public var cacheCost: Int { return kf.cost }
  84. }
  85. extension Data: DataTransformable {
  86. public func toData() throws -> Data {
  87. self
  88. }
  89. public static func fromData(_ data: Data) throws -> Data {
  90. data
  91. }
  92. public static let empty = Data()
  93. }
  94. /// Represents the result of the operation to retrieve an image from the cache.
  95. public enum ImageCacheResult: Sendable {
  96. /// The image can be retrieved from the disk cache.
  97. case disk(KFCrossPlatformImage)
  98. /// The image can be retrieved from the memory cache.
  99. case memory(KFCrossPlatformImage)
  100. /// The image does not exist in the cache.
  101. case none
  102. /// Extracts the image from cache result.
  103. ///
  104. /// It returns the associated `Image` value for ``ImageCacheResult/disk(_:)`` and ``ImageCacheResult/memory(_:)``
  105. /// case. For ``ImageCacheResult/none`` case, returns `nil`.
  106. public var image: KFCrossPlatformImage? {
  107. switch self {
  108. case .disk(let image): return image
  109. case .memory(let image): return image
  110. case .none: return nil
  111. }
  112. }
  113. /// Returns the corresponding ``CacheType`` value based on the result type of `self`.
  114. public var cacheType: CacheType {
  115. switch self {
  116. case .disk: return .disk
  117. case .memory: return .memory
  118. case .none: return .none
  119. }
  120. }
  121. }
  122. /// Represents a hybrid caching system composed of a ``MemoryStorage`` and a ``DiskStorage``.
  123. ///
  124. /// ``ImageCache`` serves as a high-level abstraction for storing an image and its data in memory and on disk, as well
  125. /// as retrieving them. You can define configurations for the memory cache backend and disk cache backend, and the the
  126. /// unified methods to store images to the cache or retrieve images from either the memory cache or the disk cache.
  127. ///
  128. /// > While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create
  129. /// your own cache object and configure its storages according to your needs. This class also provides an interface for
  130. /// configuring the memory and disk storage.
  131. open class ImageCache: @unchecked Sendable {
  132. // MARK: Singleton
  133. /// The default ``ImageCache`` object.
  134. ///
  135. /// Kingfisher uses this value for its related methods if no other cache is specified.
  136. ///
  137. /// > Warning: The `name` of this default cache is reserved as "default", and you should not use this name for any
  138. /// of your custom caches. Otherwise, different caches might become mixed up and corrupted.
  139. public static let `default` = ImageCache(name: "default")
  140. // MARK: Public Properties
  141. /// The ``MemoryStorage/Backend`` object for the memory cache used in this cache.
  142. ///
  143. /// This storage stores loaded images in memory with a reasonable expire duration and a maximum memory usage.
  144. ///
  145. /// > To modify the configuration of a storage, just set the storage ``MemoryStorage/Config`` and its properties.
  146. public let memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>
  147. /// The ``DiskStorage/Backend`` object for the disk cache used in this cache.
  148. ///
  149. /// This storage stores loaded images on disk with a reasonable expire duration and a maximum disk usage.
  150. ///
  151. /// > To modify the configuration of a storage, just set the storage ``DiskStorage/Config`` and its properties.
  152. public let diskStorage: DiskStorage.Backend<Data>
  153. private let ioQueue: DispatchQueue
  154. /// A closure that specifies the disk cache path based on a given path and the cache name.
  155. public typealias DiskCachePathClosure = @Sendable (URL, String) -> URL
  156. // MARK: Initializers
  157. /// Creates an ``ImageCache`` with a customized ``MemoryStorage`` and ``DiskStorage``.
  158. ///
  159. /// - Parameters:
  160. /// - memoryStorage: The ``MemoryStorage/Backend`` object to be used in the image memory cache.
  161. /// - diskStorage: The ``DiskStorage/Backend`` object to be used in the image disk cache.
  162. public init(
  163. memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>,
  164. diskStorage: DiskStorage.Backend<Data>)
  165. {
  166. self.memoryStorage = memoryStorage
  167. self.diskStorage = diskStorage
  168. let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(UUID().uuidString)"
  169. ioQueue = DispatchQueue(label: ioQueueName)
  170. Task { @MainActor in
  171. let notifications: [(Notification.Name, Selector)]
  172. #if !os(macOS) && !os(watchOS)
  173. notifications = [
  174. (UIApplication.didReceiveMemoryWarningNotification, #selector(clearMemoryCache)),
  175. (UIApplication.willTerminateNotification, #selector(cleanExpiredDiskCache)),
  176. (UIApplication.didEnterBackgroundNotification, #selector(backgroundCleanExpiredDiskCache))
  177. ]
  178. #elseif os(macOS)
  179. notifications = [
  180. (NSApplication.willResignActiveNotification, #selector(cleanExpiredDiskCache)),
  181. ]
  182. #else
  183. notifications = []
  184. #endif
  185. notifications.forEach {
  186. NotificationCenter.default.addObserver(self, selector: $0.1, name: $0.0, object: nil)
  187. }
  188. }
  189. }
  190. /// Creates an ``ImageCache`` with a given `name`.
  191. ///
  192. /// Both the ``MemoryStorage`` and the ``DiskStorage`` will be created with a default configuration based on the `name`.
  193. ///
  194. /// - Parameter name: The name of the cache object. It is used to set up disk cache directories and IO queues.
  195. /// You should not use the same `name` for different caches; otherwise, the disk storages would conflict with each
  196. /// other. The `name` should not be an empty string.
  197. ///
  198. /// > Warning: The `name` "default" is reserved to be used as the name of ``ImageCache/default`` in Kingfisher,
  199. /// and you should not use this name for any of your custom caches. Otherwise, different caches might become mixed
  200. /// up and corrupted.
  201. public convenience init(name: String) {
  202. self.init(noThrowName: name, cacheDirectoryURL: nil, diskCachePathClosure: nil)
  203. }
  204. /// Creates an ``ImageCache`` with a given `name`, the cache directory `path`, and a closure to modify the cache
  205. /// directory.
  206. ///
  207. /// - Parameters:
  208. /// - name: The name of the cache object. It is used to set up disk cache directories and IO queues.
  209. /// You should not use the same `name` for different caches; otherwise, the disk storages would conflict with each
  210. /// other. The `name` should not be an empty string.
  211. /// - cacheDirectoryURL: The location of the cache directory URL on disk. It will be passed internally to the
  212. /// initializer of the ``DiskStorage`` as the disk cache directory. If `nil`, the cache directory under the user
  213. /// domain mask will be used.
  214. /// - diskCachePathClosure: A closure that takes in an optional initial path string and generates the final disk
  215. /// cache path. You can use it to fully customize your cache path.
  216. /// - Throws: An error that occurs during the creation of the image cache, such as being unable to create a
  217. /// directory at the given path.
  218. ///
  219. /// > Warning: The `name` "default" is reserved to be used as the name of ``ImageCache/default`` in Kingfisher,
  220. /// and you should not use this name for any of your custom caches. Otherwise, different caches might become mixed
  221. /// up and corrupted.
  222. public convenience init(
  223. name: String,
  224. cacheDirectoryURL: URL?,
  225. diskCachePathClosure: DiskCachePathClosure? = nil
  226. ) throws
  227. {
  228. if name.isEmpty {
  229. fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
  230. }
  231. let memoryStorage = ImageCache.createMemoryStorage()
  232. let config = ImageCache.createConfig(
  233. name: name, cacheDirectoryURL: cacheDirectoryURL, diskCachePathClosure: diskCachePathClosure
  234. )
  235. let diskStorage = try DiskStorage.Backend<Data>(config: config)
  236. self.init(memoryStorage: memoryStorage, diskStorage: diskStorage)
  237. }
  238. convenience init(
  239. noThrowName name: String,
  240. cacheDirectoryURL: URL?,
  241. diskCachePathClosure: DiskCachePathClosure?
  242. )
  243. {
  244. if name.isEmpty {
  245. fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
  246. }
  247. let memoryStorage = ImageCache.createMemoryStorage()
  248. let config = ImageCache.createConfig(
  249. name: name, cacheDirectoryURL: cacheDirectoryURL, diskCachePathClosure: diskCachePathClosure
  250. )
  251. let diskStorage = DiskStorage.Backend<Data>(noThrowConfig: config, creatingDirectory: true)
  252. self.init(memoryStorage: memoryStorage, diskStorage: diskStorage)
  253. }
  254. private static func createMemoryStorage() -> MemoryStorage.Backend<KFCrossPlatformImage> {
  255. let totalMemory = ProcessInfo.processInfo.physicalMemory
  256. let costLimit = totalMemory / 4
  257. let memoryStorage = MemoryStorage.Backend<KFCrossPlatformImage>(config:
  258. .init(totalCostLimit: (costLimit > Int.max) ? Int.max : Int(costLimit)))
  259. return memoryStorage
  260. }
  261. private static func createConfig(
  262. name: String,
  263. cacheDirectoryURL: URL?,
  264. diskCachePathClosure: DiskCachePathClosure? = nil
  265. ) -> DiskStorage.Config
  266. {
  267. var diskConfig = DiskStorage.Config(
  268. name: name,
  269. sizeLimit: 0,
  270. directory: cacheDirectoryURL
  271. )
  272. if let closure = diskCachePathClosure {
  273. diskConfig.cachePathBlock = closure
  274. }
  275. return diskConfig
  276. }
  277. deinit {
  278. NotificationCenter.default.removeObserver(self)
  279. }
  280. // MARK: Storing Images
  281. /// Stores an image to the cache.
  282. ///
  283. /// - Parameters:
  284. /// - image: The image that to be stored.
  285. /// - original: The original data of the image. This value will be forwarded to the provided `serializer` for
  286. /// further use. By default, Kingfisher uses a ``DefaultCacheSerializer`` to serialize the image to data for
  287. /// caching in disk. It checks the image format based on the `original` data to determine the appropriate image
  288. /// format to use. For other types of `serializer`, it depends on their implementation details on how to use this
  289. /// original data.
  290. /// - key: The key used for caching the image.
  291. /// - options: The options which contains configurations for caching the image.
  292. /// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory.
  293. /// Otherwise, it is cached in both memory storage and disk storage. The default is `true`.
  294. /// - completionHandler: A closure which is invoked when the cache operation finishes.
  295. open func store(
  296. _ image: KFCrossPlatformImage,
  297. original: Data? = nil,
  298. forKey key: String,
  299. options: KingfisherParsedOptionsInfo,
  300. toDisk: Bool = true,
  301. completionHandler: (@Sendable (CacheStoreResult) -> Void)? = nil
  302. )
  303. {
  304. let identifier = options.processor.identifier
  305. let callbackQueue = options.callbackQueue
  306. let computedKey = key.computedKey(with: identifier)
  307. // Memory storage should not throw.
  308. memoryStorage.storeNoThrow(value: image, forKey: computedKey, expiration: options.memoryCacheExpiration)
  309. guard toDisk else {
  310. if let completionHandler = completionHandler {
  311. let result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(()))
  312. callbackQueue.execute { completionHandler(result) }
  313. }
  314. return
  315. }
  316. ioQueue.async {
  317. let serializer = options.cacheSerializer
  318. if let data = serializer.data(with: image, original: original) {
  319. self.syncStoreToDisk(
  320. data,
  321. forKey: key,
  322. processorIdentifier: identifier,
  323. callbackQueue: callbackQueue,
  324. expiration: options.diskCacheExpiration,
  325. writeOptions: options.diskStoreWriteOptions,
  326. completionHandler: completionHandler)
  327. } else {
  328. guard let completionHandler = completionHandler else { return }
  329. let diskError = KingfisherError.cacheError(
  330. reason: .cannotSerializeImage(image: image, original: original, serializer: serializer))
  331. let result = CacheStoreResult(
  332. memoryCacheResult: .success(()),
  333. diskCacheResult: .failure(diskError))
  334. callbackQueue.execute { completionHandler(result) }
  335. }
  336. }
  337. }
  338. /// Stores an image in the cache.
  339. ///
  340. /// - Parameters:
  341. /// - image: The image to be stored.
  342. /// - original: The original data of the image. This value will be forwarded to the provided `serializer` for
  343. /// further use. By default, Kingfisher uses a ``DefaultCacheSerializer`` to serialize the image to data for
  344. /// caching in disk. It checks the image format based on the `original` data to determine the appropriate image
  345. /// format to use. For other types of `serializer`, it depends on their implementation details on how to use this
  346. /// original data.
  347. /// - key: The key used for caching the image.
  348. /// - identifier: The identifier of the processor being used for caching. If you are using a processor for the
  349. /// image, pass the identifier of the processor to this parameter.
  350. /// - serializer: The ``CacheSerializer`` used to convert the `image` and `original` to the data that will be
  351. /// stored to disk. By default, the ``DefaultCacheSerializer/default`` will be used.
  352. /// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory.
  353. /// Otherwise, it is cached in both memory storage and disk storage. The default is `true`.
  354. /// - callbackQueue: The callback queue on which the `completionHandler` is invoked. The default is
  355. /// ``CallbackQueue/untouch``. Under this default ``CallbackQueue/untouch`` queue, if `toDisk` is `false`, it
  356. /// means the `completionHandler` will be invoked from the caller queue of this method; if `toDisk` is `true`,
  357. /// the `completionHandler` will be called from an internal file IO queue. To change this behavior, specify
  358. /// another ``CallbackQueue`` value.
  359. /// - completionHandler: A closure that is invoked when the cache operation finishes.
  360. open func store(
  361. _ image: KFCrossPlatformImage,
  362. original: Data? = nil,
  363. forKey key: String,
  364. processorIdentifier identifier: String = "",
  365. cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
  366. toDisk: Bool = true,
  367. callbackQueue: CallbackQueue = .untouch,
  368. completionHandler: (@Sendable (CacheStoreResult) -> Void)? = nil
  369. )
  370. {
  371. struct TempProcessor: ImageProcessor {
  372. let identifier: String
  373. func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  374. return nil
  375. }
  376. }
  377. let options = KingfisherParsedOptionsInfo([
  378. .processor(TempProcessor(identifier: identifier)),
  379. .cacheSerializer(serializer),
  380. .callbackQueue(callbackQueue)
  381. ])
  382. store(image, original: original, forKey: key, options: options,
  383. toDisk: toDisk, completionHandler: completionHandler)
  384. }
  385. open func storeToDisk(
  386. _ data: Data,
  387. forKey key: String,
  388. processorIdentifier identifier: String = "",
  389. expiration: StorageExpiration? = nil,
  390. callbackQueue: CallbackQueue = .untouch,
  391. completionHandler: (@Sendable (CacheStoreResult) -> Void)? = nil)
  392. {
  393. ioQueue.async {
  394. self.syncStoreToDisk(
  395. data,
  396. forKey: key,
  397. processorIdentifier: identifier,
  398. callbackQueue: callbackQueue,
  399. expiration: expiration,
  400. completionHandler: completionHandler)
  401. }
  402. }
  403. private func syncStoreToDisk(
  404. _ data: Data,
  405. forKey key: String,
  406. processorIdentifier identifier: String = "",
  407. callbackQueue: CallbackQueue = .untouch,
  408. expiration: StorageExpiration? = nil,
  409. writeOptions: Data.WritingOptions = [],
  410. completionHandler: (@Sendable (CacheStoreResult) -> Void)? = nil)
  411. {
  412. let computedKey = key.computedKey(with: identifier)
  413. let result: CacheStoreResult
  414. do {
  415. try self.diskStorage.store(value: data, forKey: computedKey, expiration: expiration, writeOptions: writeOptions)
  416. result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(()))
  417. } catch {
  418. let diskError: KingfisherError
  419. if let error = error as? KingfisherError {
  420. diskError = error
  421. } else {
  422. diskError = .cacheError(reason: .cannotConvertToData(object: data, error: error))
  423. }
  424. result = CacheStoreResult(
  425. memoryCacheResult: .success(()),
  426. diskCacheResult: .failure(diskError)
  427. )
  428. }
  429. if let completionHandler = completionHandler {
  430. callbackQueue.execute { completionHandler(result) }
  431. }
  432. }
  433. // MARK: Removing Images
  434. /// Removes the image for the given key from the cache.
  435. ///
  436. /// - Parameters:
  437. /// - key: The key used for caching the image.
  438. /// - identifier: The identifier of the processor being used for caching. If you are using a processor for the
  439. /// image, pass the identifier of the processor to this parameter.
  440. /// - fromMemory: Whether this image should be removed from memory storage or not. If `false`, the image won't be
  441. /// removed from the memory storage. The default is `true`.
  442. /// - fromDisk: Whether this image should be removed from the disk storage or not. If `false`, the image won't be
  443. /// removed from the disk storage. The default is `true`.
  444. /// - callbackQueue: The callback queue on which the `completionHandler` is invoked. The default is
  445. /// ``CallbackQueue/untouch``.
  446. /// - completionHandler: A closure that is invoked when the cache removal operation finishes.
  447. open func removeImage(
  448. forKey key: String,
  449. processorIdentifier identifier: String = "",
  450. fromMemory: Bool = true,
  451. fromDisk: Bool = true,
  452. callbackQueue: CallbackQueue = .untouch,
  453. completionHandler: (@Sendable () -> Void)? = nil
  454. )
  455. {
  456. removeImage(
  457. forKey: key,
  458. processorIdentifier: identifier,
  459. fromMemory: fromMemory,
  460. fromDisk: fromDisk,
  461. callbackQueue: callbackQueue,
  462. completionHandler: { _ in completionHandler?() } // This is a version which ignores error.
  463. )
  464. }
  465. func removeImage(forKey key: String,
  466. processorIdentifier identifier: String = "",
  467. fromMemory: Bool = true,
  468. fromDisk: Bool = true,
  469. callbackQueue: CallbackQueue = .untouch,
  470. completionHandler: (@Sendable (Error?) -> Void)? = nil)
  471. {
  472. let computedKey = key.computedKey(with: identifier)
  473. if fromMemory {
  474. memoryStorage.remove(forKey: computedKey)
  475. }
  476. @Sendable func callHandler(_ error: Error?) {
  477. if let completionHandler = completionHandler {
  478. callbackQueue.execute { completionHandler(error) }
  479. }
  480. }
  481. if fromDisk {
  482. ioQueue.async{
  483. do {
  484. try self.diskStorage.remove(forKey: computedKey)
  485. callHandler(nil)
  486. } catch {
  487. callHandler(error)
  488. }
  489. }
  490. } else {
  491. callHandler(nil)
  492. }
  493. }
  494. // MARK: Getting Images
  495. /// Retrieves an image for a given key from the cache, either from memory storage or disk storage.
  496. ///
  497. /// - Parameters:
  498. /// - key: The key used for caching the image.
  499. /// - options: The ``KingfisherParsedOptionsInfo`` options setting used for retrieving the image.
  500. /// - callbackQueue: The callback queue on which the `completionHandler` is invoked.
  501. /// The default is ``CallbackQueue/mainCurrentOrAsync``.
  502. /// - completionHandler: A closure that is invoked when the image retrieval operation finishes. If the image
  503. /// retrieval operation finishes without any problems, an ``ImageCacheResult`` value will be sent to this closure
  504. /// as a result. Otherwise, a ``KingfisherError`` result with detailed failure reason will be sent.
  505. open func retrieveImage(
  506. forKey key: String,
  507. options: KingfisherParsedOptionsInfo,
  508. callbackQueue: CallbackQueue = .mainCurrentOrAsync,
  509. completionHandler: (@Sendable (Result<ImageCacheResult, KingfisherError>) -> Void)?)
  510. {
  511. // No completion handler. No need to start working and early return.
  512. guard let completionHandler = completionHandler else { return }
  513. // Try to check the image from memory cache first.
  514. if let image = retrieveImageInMemoryCache(forKey: key, options: options) {
  515. callbackQueue.execute { completionHandler(.success(.memory(image))) }
  516. } else if options.fromMemoryCacheOrRefresh {
  517. callbackQueue.execute { completionHandler(.success(.none)) }
  518. } else {
  519. // Begin to disk search.
  520. self.retrieveImageInDiskCache(forKey: key, options: options, callbackQueue: callbackQueue) {
  521. result in
  522. switch result {
  523. case .success(let image):
  524. guard let image = image else {
  525. // No image found in disk storage.
  526. callbackQueue.execute { completionHandler(.success(.none)) }
  527. return
  528. }
  529. // Cache the disk image to memory.
  530. // We are passing `false` to `toDisk`, the memory cache does not change
  531. // callback queue, we can call `completionHandler` without another dispatch.
  532. var cacheOptions = options
  533. cacheOptions.callbackQueue = .untouch
  534. self.store(
  535. image,
  536. forKey: key,
  537. options: cacheOptions,
  538. toDisk: false)
  539. {
  540. _ in
  541. callbackQueue.execute { completionHandler(.success(.disk(image))) }
  542. }
  543. case .failure(let error):
  544. callbackQueue.execute { completionHandler(.failure(error)) }
  545. }
  546. }
  547. }
  548. }
  549. /// Retrieves an image for a given key from the cache, either from memory storage or disk storage.
  550. ///
  551. ///
  552. /// - Parameters:
  553. /// - key: The key used for caching the image.
  554. /// - options: The ``KingfisherOptionsInfo`` options setting used for retrieving the image.
  555. /// - callbackQueue: The callback queue on which the `completionHandler` is invoked.
  556. /// The default is ``CallbackQueue/mainCurrentOrAsync``.
  557. /// - completionHandler: A closure that is invoked when the image retrieval operation finishes. If the image
  558. /// retrieval operation finishes without any problems, an ``ImageCacheResult`` value will be sent to this closure
  559. /// as a result. Otherwise, a ``KingfisherError`` result with detailed failure reason will be sent.
  560. ///
  561. /// > This method is marked as `open` for compatibility purposes only. Do not override this method. Instead,
  562. /// override the version ``ImageCache/retrieveImage(forKey:options:callbackQueue:completionHandler:)-1m1bb`` that
  563. /// accepts a ``KingfisherParsedOptionsInfo`` value.
  564. open func retrieveImage(
  565. forKey key: String,
  566. options: KingfisherOptionsInfo? = nil,
  567. callbackQueue: CallbackQueue = .mainCurrentOrAsync,
  568. completionHandler: (@Sendable (Result<ImageCacheResult, KingfisherError>) -> Void)?
  569. )
  570. {
  571. retrieveImage(
  572. forKey: key,
  573. options: KingfisherParsedOptionsInfo(options),
  574. callbackQueue: callbackQueue,
  575. completionHandler: completionHandler)
  576. }
  577. /// Retrieves an image associated with a given key from the memory storage.
  578. ///
  579. /// - Parameters:
  580. /// - key: The key used for caching the image.
  581. /// - options: The ``KingfisherParsedOptionsInfo`` options setting used to fetch the image.
  582. /// - Returns: The image stored in the memory cache if it exists and is valid. If the image does not exist or has
  583. /// already expired, `nil` is returned.
  584. open func retrieveImageInMemoryCache(
  585. forKey key: String,
  586. options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?
  587. {
  588. let computedKey = key.computedKey(with: options.processor.identifier)
  589. return memoryStorage.value(
  590. forKey: computedKey,
  591. extendingExpiration: options.memoryCacheAccessExtendingExpiration
  592. )
  593. }
  594. /// Retrieves an image associated with a given key from the memory storage.
  595. ///
  596. /// - Parameters:
  597. /// - key: The key used for caching the image.
  598. /// - options: The ``KingfisherOptionsInfo`` options setting used to fetch the image.
  599. /// - Returns: The image stored in the memory cache if it exists and is valid. If the image does not exist or has
  600. /// already expired, `nil` is returned.
  601. ///
  602. /// > This method is marked as `open` for compatibility purposes only. Do not override this method. Instead,
  603. /// override the version ``ImageCache/retrieveImageInMemoryCache(forKey:options:)-2xj0`` that accepts a
  604. /// ``KingfisherParsedOptionsInfo`` value.
  605. open func retrieveImageInMemoryCache(
  606. forKey key: String,
  607. options: KingfisherOptionsInfo? = nil) -> KFCrossPlatformImage?
  608. {
  609. return retrieveImageInMemoryCache(forKey: key, options: KingfisherParsedOptionsInfo(options))
  610. }
  611. func retrieveImageInDiskCache(
  612. forKey key: String,
  613. options: KingfisherParsedOptionsInfo,
  614. callbackQueue: CallbackQueue = .untouch,
  615. completionHandler: @escaping @Sendable (Result<KFCrossPlatformImage?, KingfisherError>) -> Void)
  616. {
  617. let computedKey = key.computedKey(with: options.processor.identifier)
  618. let loadingQueue: CallbackQueue = options.loadDiskFileSynchronously ? .untouch : .dispatch(ioQueue)
  619. loadingQueue.execute {
  620. do {
  621. var image: KFCrossPlatformImage? = nil
  622. if let data = try self.diskStorage.value(forKey: computedKey, extendingExpiration: options.diskCacheAccessExtendingExpiration) {
  623. image = options.cacheSerializer.image(with: data, options: options)
  624. }
  625. if options.backgroundDecode {
  626. image = image?.kf.decoded(scale: options.scaleFactor)
  627. }
  628. callbackQueue.execute { [image] in completionHandler(.success(image)) }
  629. } catch let error as KingfisherError {
  630. callbackQueue.execute { completionHandler(.failure(error)) }
  631. } catch {
  632. assertionFailure("The internal thrown error should be a `KingfisherError`.")
  633. }
  634. }
  635. }
  636. /// Retrieves an image associated with a given key from the disk storage.
  637. ///
  638. /// - Parameters:
  639. /// - key: The key used for caching the image.
  640. /// - options: The ``KingfisherOptionsInfo`` options setting used to fetch the image.
  641. /// - callbackQueue: The callback queue on which the `completionHandler` is invoked.
  642. /// The default is ``CallbackQueue/untouch``.
  643. /// - completionHandler: A closure that is invoked when the operation is finished.
  644. open func retrieveImageInDiskCache(
  645. forKey key: String,
  646. options: KingfisherOptionsInfo? = nil,
  647. callbackQueue: CallbackQueue = .untouch,
  648. completionHandler: @escaping @Sendable (Result<KFCrossPlatformImage?, KingfisherError>) -> Void)
  649. {
  650. retrieveImageInDiskCache(
  651. forKey: key,
  652. options: KingfisherParsedOptionsInfo(options),
  653. callbackQueue: callbackQueue,
  654. completionHandler: completionHandler)
  655. }
  656. // MARK: Cleaning
  657. /// Clears the memory and disk storage of this cache.
  658. ///
  659. /// This is an asynchronous operation. When the cache clearing operation finishes, the `handler` will be invoked.
  660. ///
  661. /// - Parameter handler: A closure that is invoked when the cache clearing operation finishes.
  662. /// This `handler` will be called from the main queue.
  663. public func clearCache(completion handler: (@Sendable () -> Void)? = nil) {
  664. clearMemoryCache()
  665. clearDiskCache(completion: handler)
  666. }
  667. /// Clears the memory storage of this cache.
  668. @objc public func clearMemoryCache() {
  669. memoryStorage.removeAll()
  670. }
  671. /// Clears the disk storage of this cache.
  672. ///
  673. /// This is an asynchronous operation. When the cache clearing operation finishes, the `handler` will be invoked.
  674. ///
  675. /// - Parameter handler: A closure that is invoked when the cache clearing operation finishes.
  676. /// This `handler` will be called from the main queue.
  677. open func clearDiskCache(completion handler: (@Sendable () -> Void)? = nil) {
  678. ioQueue.async {
  679. do {
  680. try self.diskStorage.removeAll()
  681. } catch _ { }
  682. if let handler = handler {
  683. DispatchQueue.main.async { handler() }
  684. }
  685. }
  686. }
  687. /// Clears the expired images from the memory and disk storage.
  688. ///
  689. /// This is an asynchronous operation. When the cache clearing operation finishes, the `handler` will be invoked.
  690. open func cleanExpiredCache(completion handler: (@Sendable () -> Void)? = nil) {
  691. cleanExpiredMemoryCache()
  692. cleanExpiredDiskCache(completion: handler)
  693. }
  694. /// Clears the expired images from the memory storage.
  695. open func cleanExpiredMemoryCache() {
  696. memoryStorage.removeExpired()
  697. }
  698. /// Clears the expired images from disk storage.
  699. ///
  700. /// This is an async operation.
  701. @objc func cleanExpiredDiskCache() {
  702. cleanExpiredDiskCache(completion: nil)
  703. }
  704. /// Clears the expired images from disk storage.
  705. ///
  706. /// This is an asynchronous operation. When the cache clearing operation finishes, the `handler` will be invoked.
  707. ///
  708. /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes.
  709. /// This `handler` will be called from the main queue.
  710. open func cleanExpiredDiskCache(completion handler: (@Sendable () -> Void)? = nil) {
  711. ioQueue.async {
  712. do {
  713. var removed: [URL] = []
  714. let removedExpired = try self.diskStorage.removeExpiredValues()
  715. removed.append(contentsOf: removedExpired)
  716. let removedSizeExceeded = try self.diskStorage.removeSizeExceededValues()
  717. removed.append(contentsOf: removedSizeExceeded)
  718. if !removed.isEmpty {
  719. DispatchQueue.main.async { [removed] in
  720. let cleanedHashes = removed.map { $0.lastPathComponent }
  721. NotificationCenter.default.post(
  722. name: .KingfisherDidCleanDiskCache,
  723. object: self,
  724. userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
  725. }
  726. }
  727. if let handler = handler {
  728. DispatchQueue.main.async { handler() }
  729. }
  730. } catch {}
  731. }
  732. }
  733. #if !os(macOS) && !os(watchOS)
  734. /// Clears the expired images from disk storage when the app is in the background.
  735. ///
  736. /// This is an asynchronous operation. When the cache clearing operation finishes, the `handler` will be invoked.
  737. ///
  738. /// In most cases, you should not call this method explicitly. It will be called automatically when a
  739. /// `UIApplicationDidEnterBackgroundNotification` is received.
  740. @MainActor
  741. @objc public func backgroundCleanExpiredDiskCache() {
  742. // if 'sharedApplication()' is unavailable, then return
  743. guard let sharedApplication = KingfisherWrapper<UIApplication>.shared else { return }
  744. let taskActor = ActorBox<UIBackgroundTaskIdentifier?>(nil)
  745. let createdTask = sharedApplication.beginBackgroundTask(withName: "Kingfisher:backgroundCleanExpiredDiskCache") {
  746. Task {
  747. guard let bgTask = await taskActor.value, bgTask != .invalid else { return }
  748. sharedApplication.endBackgroundTask(bgTask)
  749. await taskActor.setValue(.invalid)
  750. }
  751. }
  752. cleanExpiredDiskCache {
  753. Task {
  754. guard let bgTask = await taskActor.value, bgTask != .invalid else { return }
  755. #if swift(>=6)
  756. sharedApplication.endBackgroundTask(bgTask)
  757. #else
  758. await sharedApplication.endBackgroundTask(bgTask)
  759. #endif
  760. await taskActor.setValue(.invalid)
  761. }
  762. }
  763. Task {
  764. await taskActor.setValue(createdTask)
  765. }
  766. }
  767. #endif
  768. // MARK: Image Cache State
  769. /// Returns the cache type for a given `key` and `identifier` combination.
  770. ///
  771. /// This method is used to check whether an image is cached in the current cache. It also provides information on
  772. /// which kind of cache the image can be found in the return value.
  773. ///
  774. /// - Parameters:
  775. /// - key: The key used for caching the image.
  776. /// - identifier: The processor identifier used for this image. The default value is the
  777. /// ``DefaultImageProcessor/identifier`` of the ``DefaultImageProcessor/default`` image processor.
  778. /// - Returns: A ``CacheType`` instance that indicates the cache status. ``CacheType/none`` indicates that the
  779. /// image is not in the cache or that it has already expired.
  780. open func imageCachedType(
  781. forKey key: String,
  782. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> CacheType
  783. {
  784. let computedKey = key.computedKey(with: identifier)
  785. if memoryStorage.isCached(forKey: computedKey) { return .memory }
  786. if diskStorage.isCached(forKey: computedKey) { return .disk }
  787. return .none
  788. }
  789. /// Returns whether the file exists in the cache for a given `key` and `identifier` combination.
  790. ///
  791. /// - Parameters:
  792. /// - key: The key used for caching the image.
  793. /// - identifier: The processor identifier used for this image. The default value is the
  794. /// ``DefaultImageProcessor/identifier`` of the ``DefaultImageProcessor/default`` image processor.
  795. /// - Returns: A `Bool` value indicating whether a cache matches the given `key` and `identifier` combination.
  796. ///
  797. /// > The return value does not contain information about the kind of storage the cache matches from.
  798. /// > To obtain information about the cache type according to ``CacheType``, use
  799. /// ``ImageCache/imageCachedType(forKey:processorIdentifier:)`` instead.
  800. public func isCached(
  801. forKey key: String,
  802. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> Bool
  803. {
  804. return imageCachedType(forKey: key, processorIdentifier: identifier).cached
  805. }
  806. /// Retrieves the hash used as the cache file name for the key.
  807. ///
  808. /// - Parameters:
  809. /// - key: The key used for caching the image.
  810. /// - identifier: The processor identifier used for this image. The default value is the
  811. /// ``DefaultImageProcessor/identifier`` of the ``DefaultImageProcessor/default`` image processor.
  812. /// - Returns: The hash used as the cache file name.
  813. ///
  814. /// > By default, for a given combination of `key` and `identifier`, the ``ImageCache`` instance uses the value
  815. /// returned by this method as the cache file name. You can use this value to check and match the cache file if
  816. /// needed.
  817. open func hash(
  818. forKey key: String,
  819. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
  820. {
  821. let computedKey = key.computedKey(with: identifier)
  822. return diskStorage.cacheFileName(forKey: computedKey)
  823. }
  824. /// Calculates the size taken by the disk storage.
  825. ///
  826. /// It represents the total file size of all cached files in the ``ImageCache/diskStorage`` on disk in bytes.
  827. ///
  828. /// - Parameter handler: Called when the size calculation is complete. This closure is invoked from the main queue.
  829. open func calculateDiskStorageSize(
  830. completion handler: @escaping (@Sendable (Result<UInt, KingfisherError>) -> Void)
  831. ) {
  832. ioQueue.async {
  833. do {
  834. let size = try self.diskStorage.totalSize()
  835. DispatchQueue.main.async { handler(.success(size)) }
  836. } catch let error as KingfisherError {
  837. DispatchQueue.main.async { handler(.failure(error)) }
  838. } catch {
  839. assertionFailure("The internal thrown error should be a `KingfisherError`.")
  840. }
  841. }
  842. }
  843. /// Retrieves the cache path for the key.
  844. ///
  845. /// It is useful for projects with a web view or for anyone who needs access to the local file path.
  846. /// For instance, replacing the `<img src='path_for_key'>` tag in your HTML.
  847. ///
  848. /// - Parameters:
  849. /// - key: The key used for caching the image.
  850. /// - identifier: The processor identifier used for this image. The default value is the
  851. /// ``DefaultImageProcessor/identifier`` of the ``DefaultImageProcessor/default`` image processor.
  852. /// - Returns: The disk path of the cached image under the given `key` and `identifier`.
  853. ///
  854. /// > This method does not guarantee that there is an image already cached in the returned path. It simply provides
  855. /// > the path where the image should be if it exists in the disk storage.
  856. /// >
  857. /// > You could use the ``ImageCache/isCached(forKey:processorIdentifier:)`` method to check whether the image is
  858. /// cached under that key on disk if necessary.
  859. open func cachePath(
  860. forKey key: String,
  861. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
  862. {
  863. let computedKey = key.computedKey(with: identifier)
  864. return diskStorage.cacheFileURL(forKey: computedKey).path
  865. }
  866. // MARK: - Concurrency
  867. /// Stores an image to the cache.
  868. ///
  869. /// - Parameters:
  870. /// - image: The image that to be stored.
  871. /// - original: The original data of the image. This value will be forwarded to the provided `serializer` for
  872. /// further use. By default, Kingfisher uses a ``DefaultCacheSerializer`` to serialize the image to data for
  873. /// caching in disk. It checks the image format based on the `original` data to determine the appropriate image
  874. /// format to use. For other types of `serializer`, it depends on their implementation details on how to use this
  875. /// original data.
  876. /// - key: The key used for caching the image.
  877. /// - options: The options which contains configurations for caching the image.
  878. /// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory.
  879. /// Otherwise, it is cached in both memory storage and disk storage. The default is `true`.
  880. open func store(
  881. _ image: KFCrossPlatformImage,
  882. original: Data? = nil,
  883. forKey key: String,
  884. options: KingfisherParsedOptionsInfo,
  885. toDisk: Bool = true
  886. ) async throws {
  887. try await withCheckedThrowingContinuation { continuation in
  888. store(image, original: original, forKey: key, options: options, toDisk: toDisk) {
  889. continuation.resume(with: $0.diskCacheResult)
  890. }
  891. }
  892. }
  893. /// Stores an image in the cache.
  894. ///
  895. /// - Parameters:
  896. /// - image: The image to be stored.
  897. /// - original: The original data of the image. This value will be forwarded to the provided `serializer` for
  898. /// further use. By default, Kingfisher uses a ``DefaultCacheSerializer`` to serialize the image to data for
  899. /// caching in disk. It checks the image format based on the `original` data to determine the appropriate image
  900. /// format to use. For other types of `serializer`, it depends on their implementation details on how to use this
  901. /// original data.
  902. /// - key: The key used for caching the image.
  903. /// - identifier: The identifier of the processor being used for caching. If you are using a processor for the
  904. /// image, pass the identifier of the processor to this parameter.
  905. /// - serializer: The ``CacheSerializer`` used to convert the `image` and `original` to the data that will be
  906. /// stored to disk. By default, the ``DefaultCacheSerializer/default`` will be used.
  907. /// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory.
  908. /// Otherwise, it is cached in both memory storage and disk storage. The default is `true`.
  909. open func store(
  910. _ image: KFCrossPlatformImage,
  911. original: Data? = nil,
  912. forKey key: String,
  913. processorIdentifier identifier: String = "",
  914. cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
  915. toDisk: Bool = true
  916. ) async throws {
  917. try await withCheckedThrowingContinuation { continuation in
  918. store(
  919. image,
  920. original: original,
  921. forKey: key,
  922. processorIdentifier: identifier,
  923. cacheSerializer: serializer,
  924. toDisk: toDisk) {
  925. // Only `diskCacheResult` can fail
  926. continuation.resume(with: $0.diskCacheResult)
  927. }
  928. }
  929. }
  930. open func storeToDisk(
  931. _ data: Data,
  932. forKey key: String,
  933. processorIdentifier identifier: String = "",
  934. expiration: StorageExpiration? = nil
  935. ) async throws
  936. {
  937. try await withCheckedThrowingContinuation { continuation in
  938. storeToDisk(
  939. data,
  940. forKey: key,
  941. processorIdentifier: identifier,
  942. expiration: expiration) {
  943. // Only `diskCacheResult` can fail
  944. continuation.resume(with: $0.diskCacheResult)
  945. }
  946. }
  947. }
  948. /// Removes the image for the given key from the cache.
  949. ///
  950. /// - Parameters:
  951. /// - key: The key used for caching the image.
  952. /// - identifier: The identifier of the processor being used for caching. If you are using a processor for the
  953. /// image, pass the identifier of the processor to this parameter.
  954. /// - fromMemory: Whether this image should be removed from memory storage or not. If `false`, the image won't be
  955. /// removed from the memory storage. The default is `true`.
  956. /// - fromDisk: Whether this image should be removed from the disk storage or not. If `false`, the image won't be
  957. /// removed from the disk storage. The default is `true`.
  958. open func removeImage(
  959. forKey key: String,
  960. processorIdentifier identifier: String = "",
  961. fromMemory: Bool = true,
  962. fromDisk: Bool = true
  963. ) async throws {
  964. return try await withCheckedThrowingContinuation { continuation in
  965. removeImage(
  966. forKey: key,
  967. processorIdentifier: identifier,
  968. fromMemory: fromMemory,
  969. fromDisk: fromDisk,
  970. completionHandler: { error in
  971. if let error {
  972. continuation.resume(throwing: error)
  973. } else {
  974. continuation.resume()
  975. }
  976. }
  977. )
  978. }
  979. }
  980. /// Retrieves an image for a given key from the cache, either from memory storage or disk storage.
  981. ///
  982. /// - Parameters:
  983. /// - key: The key used for caching the image.
  984. /// - options: The ``KingfisherParsedOptionsInfo`` options setting used for retrieving the image.
  985. /// - Returns:
  986. /// If the image retrieving operation finishes without problem, an ``ImageCacheResult`` value.
  987. ///
  988. /// - Throws: An error of type ``KingfisherError``, if any error happens inside Kingfisher framework.
  989. open func retrieveImage(
  990. forKey key: String,
  991. options: KingfisherParsedOptionsInfo
  992. ) async throws -> ImageCacheResult {
  993. try await withCheckedThrowingContinuation { continuation in
  994. retrieveImage(forKey: key, options: options) { continuation.resume(with: $0) }
  995. }
  996. }
  997. /// Retrieves an image for a given key from the cache, either from memory storage or disk storage.
  998. ///
  999. /// - Parameters:
  1000. /// - key: The key used for caching the image.
  1001. /// - options: The ``KingfisherOptionsInfo`` options setting used for retrieving the image.
  1002. ///
  1003. /// - Returns: If the image retrieving operation finishes without problem, an ``ImageCacheResult`` value.
  1004. ///
  1005. /// - Throws: An error of type ``KingfisherError``, if any error happens inside Kingfisher framework.
  1006. ///
  1007. /// > This method is marked as `open` for compatibility purposes only. Do not override this method. Instead,
  1008. /// override the version ``ImageCache/retrieveImage(forKey:options:callbackQueue:completionHandler:)-1m1bb`` that
  1009. /// accepts a ``KingfisherParsedOptionsInfo`` value.
  1010. open func retrieveImage(
  1011. forKey key: String,
  1012. options: KingfisherOptionsInfo? = nil
  1013. ) async throws -> ImageCacheResult {
  1014. try await withCheckedThrowingContinuation { continuation in
  1015. retrieveImage(forKey: key, options: options) { continuation.resume(with: $0) }
  1016. }
  1017. }
  1018. /// Retrieves an image associated with a given key from the disk storage.
  1019. ///
  1020. /// - Parameters:
  1021. /// - key: The key used for caching the image.
  1022. /// - options: The ``KingfisherOptionsInfo`` options setting used to fetch the image.
  1023. ///
  1024. /// - Returns: The image stored in the disk cache if it exists and is valid. If the image does not exist or has
  1025. /// already expired, `nil` is returned.
  1026. ///
  1027. /// - Returns: If the image retrieving operation finishes without problem, an ``ImageCacheResult`` value.
  1028. ///
  1029. /// - Throws: An error of type ``KingfisherError``, if any error happens inside Kingfisher framework.
  1030. /// ``KingfisherParsedOptionsInfo`` value.
  1031. open func retrieveImageInDiskCache(
  1032. forKey key: String,
  1033. options: KingfisherOptionsInfo? = nil
  1034. ) async throws -> KFCrossPlatformImage? {
  1035. try await withCheckedThrowingContinuation { continuation in
  1036. retrieveImageInDiskCache(forKey: key, options: options) {
  1037. continuation.resume(with: $0)
  1038. }
  1039. }
  1040. }
  1041. /// Clears the memory and disk storage of this cache.
  1042. ///
  1043. /// This is an asynchronous operation. When the cache clearing operation finishes, the whole method returns.
  1044. open func clearCache() async {
  1045. await withCheckedContinuation { continuation in
  1046. clearCache { continuation.resume() }
  1047. }
  1048. }
  1049. /// Clears the disk storage of this cache.
  1050. ///
  1051. /// This is an asynchronous operation. When the cache clearing operation finishes, the whole method returns.
  1052. open func clearDiskCache() async {
  1053. await withCheckedContinuation { continuation in
  1054. clearDiskCache { continuation.resume() }
  1055. }
  1056. }
  1057. /// Clears the expired images from the memory and disk storage.
  1058. ///
  1059. /// This is an asynchronous operation. When the cache clearing operation finishes, the whole method returns.
  1060. open func cleanExpiredCache() async {
  1061. await withCheckedContinuation { continuation in
  1062. cleanExpiredCache { continuation.resume() }
  1063. }
  1064. }
  1065. /// Clears the expired images from disk storage.
  1066. ///
  1067. /// This is an asynchronous operation. When the cache clearing operation finishes, the whole method returns.
  1068. open func cleanExpiredDiskCache() async {
  1069. await withCheckedContinuation { continuation in
  1070. cleanExpiredDiskCache { continuation.resume() }
  1071. }
  1072. }
  1073. /// Calculates the size taken by the disk storage.
  1074. ///
  1075. /// It represents the total file size of all cached files in the ``ImageCache/diskStorage`` on disk in bytes.
  1076. open var diskStorageSize: UInt {
  1077. get async throws {
  1078. try await withCheckedThrowingContinuation { continuation in
  1079. calculateDiskStorageSize { continuation.resume(with: $0) }
  1080. }
  1081. }
  1082. }
  1083. }
  1084. // Concurrency
  1085. #if !os(macOS) && !os(watchOS)
  1086. // MARK: - For App Extensions
  1087. extension UIApplication: KingfisherCompatible { }
  1088. extension KingfisherWrapper where Base: UIApplication {
  1089. public static var shared: UIApplication? {
  1090. let selector = NSSelectorFromString("sharedApplication")
  1091. guard Base.responds(to: selector) else { return nil }
  1092. return Base.perform(selector).takeUnretainedValue() as? UIApplication
  1093. }
  1094. }
  1095. #endif
  1096. extension String {
  1097. func computedKey(with identifier: String) -> String {
  1098. if identifier.isEmpty {
  1099. return self
  1100. } else {
  1101. return appending("@\(identifier)")
  1102. }
  1103. }
  1104. }