ImageCache.swift 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  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. await sharedApplication.endBackgroundTask(bgTask)
  756. await taskActor.setValue(.invalid)
  757. }
  758. }
  759. Task {
  760. await taskActor.setValue(createdTask)
  761. }
  762. }
  763. #endif
  764. // MARK: Image Cache State
  765. /// Returns the cache type for a given `key` and `identifier` combination.
  766. ///
  767. /// This method is used to check whether an image is cached in the current cache. It also provides information on
  768. /// which kind of cache the image can be found in the return value.
  769. ///
  770. /// - Parameters:
  771. /// - key: The key used for caching the image.
  772. /// - identifier: The processor identifier used for this image. The default value is the
  773. /// ``DefaultImageProcessor/identifier`` of the ``DefaultImageProcessor/default`` image processor.
  774. /// - Returns: A ``CacheType`` instance that indicates the cache status. ``CacheType/none`` indicates that the
  775. /// image is not in the cache or that it has already expired.
  776. open func imageCachedType(
  777. forKey key: String,
  778. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> CacheType
  779. {
  780. let computedKey = key.computedKey(with: identifier)
  781. if memoryStorage.isCached(forKey: computedKey) { return .memory }
  782. if diskStorage.isCached(forKey: computedKey) { return .disk }
  783. return .none
  784. }
  785. /// Returns whether the file exists in the cache for a given `key` and `identifier` combination.
  786. ///
  787. /// - Parameters:
  788. /// - key: The key used for caching the image.
  789. /// - identifier: The processor identifier used for this image. The default value is the
  790. /// ``DefaultImageProcessor/identifier`` of the ``DefaultImageProcessor/default`` image processor.
  791. /// - Returns: A `Bool` value indicating whether a cache matches the given `key` and `identifier` combination.
  792. ///
  793. /// > The return value does not contain information about the kind of storage the cache matches from.
  794. /// > To obtain information about the cache type according to ``CacheType``, use
  795. /// ``ImageCache/imageCachedType(forKey:processorIdentifier:)`` instead.
  796. public func isCached(
  797. forKey key: String,
  798. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> Bool
  799. {
  800. return imageCachedType(forKey: key, processorIdentifier: identifier).cached
  801. }
  802. /// Retrieves the hash used as the cache file name for the key.
  803. ///
  804. /// - Parameters:
  805. /// - key: The key used for caching the image.
  806. /// - identifier: The processor identifier used for this image. The default value is the
  807. /// ``DefaultImageProcessor/identifier`` of the ``DefaultImageProcessor/default`` image processor.
  808. /// - Returns: The hash used as the cache file name.
  809. ///
  810. /// > By default, for a given combination of `key` and `identifier`, the ``ImageCache`` instance uses the value
  811. /// returned by this method as the cache file name. You can use this value to check and match the cache file if
  812. /// needed.
  813. open func hash(
  814. forKey key: String,
  815. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
  816. {
  817. let computedKey = key.computedKey(with: identifier)
  818. return diskStorage.cacheFileName(forKey: computedKey)
  819. }
  820. /// Calculates the size taken by the disk storage.
  821. ///
  822. /// It represents the total file size of all cached files in the ``ImageCache/diskStorage`` on disk in bytes.
  823. ///
  824. /// - Parameter handler: Called when the size calculation is complete. This closure is invoked from the main queue.
  825. open func calculateDiskStorageSize(
  826. completion handler: @escaping (@Sendable (Result<UInt, KingfisherError>) -> Void)
  827. ) {
  828. ioQueue.async {
  829. do {
  830. let size = try self.diskStorage.totalSize()
  831. DispatchQueue.main.async { handler(.success(size)) }
  832. } catch let error as KingfisherError {
  833. DispatchQueue.main.async { handler(.failure(error)) }
  834. } catch {
  835. assertionFailure("The internal thrown error should be a `KingfisherError`.")
  836. }
  837. }
  838. }
  839. /// Retrieves the cache path for the key.
  840. ///
  841. /// It is useful for projects with a web view or for anyone who needs access to the local file path.
  842. /// For instance, replacing the `<img src='path_for_key'>` tag in your HTML.
  843. ///
  844. /// - Parameters:
  845. /// - key: The key used for caching the image.
  846. /// - identifier: The processor identifier used for this image. The default value is the
  847. /// ``DefaultImageProcessor/identifier`` of the ``DefaultImageProcessor/default`` image processor.
  848. /// - Returns: The disk path of the cached image under the given `key` and `identifier`.
  849. ///
  850. /// > This method does not guarantee that there is an image already cached in the returned path. It simply provides
  851. /// > the path where the image should be if it exists in the disk storage.
  852. /// >
  853. /// > You could use the ``ImageCache/isCached(forKey:processorIdentifier:)`` method to check whether the image is
  854. /// cached under that key on disk if necessary.
  855. open func cachePath(
  856. forKey key: String,
  857. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
  858. {
  859. let computedKey = key.computedKey(with: identifier)
  860. return diskStorage.cacheFileURL(forKey: computedKey).path
  861. }
  862. // MARK: - Concurrency
  863. /// Stores an image to the cache.
  864. ///
  865. /// - Parameters:
  866. /// - image: The image that to be stored.
  867. /// - original: The original data of the image. This value will be forwarded to the provided `serializer` for
  868. /// further use. By default, Kingfisher uses a ``DefaultCacheSerializer`` to serialize the image to data for
  869. /// caching in disk. It checks the image format based on the `original` data to determine the appropriate image
  870. /// format to use. For other types of `serializer`, it depends on their implementation details on how to use this
  871. /// original data.
  872. /// - key: The key used for caching the image.
  873. /// - options: The options which contains configurations for caching the image.
  874. /// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory.
  875. /// Otherwise, it is cached in both memory storage and disk storage. The default is `true`.
  876. open func store(
  877. _ image: KFCrossPlatformImage,
  878. original: Data? = nil,
  879. forKey key: String,
  880. options: KingfisherParsedOptionsInfo,
  881. toDisk: Bool = true
  882. ) async throws {
  883. try await withCheckedThrowingContinuation { continuation in
  884. store(image, original: original, forKey: key, options: options, toDisk: toDisk) {
  885. continuation.resume(with: $0.diskCacheResult)
  886. }
  887. }
  888. }
  889. /// Stores an image in the cache.
  890. ///
  891. /// - Parameters:
  892. /// - image: The image to be stored.
  893. /// - original: The original data of the image. This value will be forwarded to the provided `serializer` for
  894. /// further use. By default, Kingfisher uses a ``DefaultCacheSerializer`` to serialize the image to data for
  895. /// caching in disk. It checks the image format based on the `original` data to determine the appropriate image
  896. /// format to use. For other types of `serializer`, it depends on their implementation details on how to use this
  897. /// original data.
  898. /// - key: The key used for caching the image.
  899. /// - identifier: The identifier of the processor being used for caching. If you are using a processor for the
  900. /// image, pass the identifier of the processor to this parameter.
  901. /// - serializer: The ``CacheSerializer`` used to convert the `image` and `original` to the data that will be
  902. /// stored to disk. By default, the ``DefaultCacheSerializer/default`` will be used.
  903. /// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory.
  904. /// Otherwise, it is cached in both memory storage and disk storage. The default is `true`.
  905. open func store(
  906. _ image: KFCrossPlatformImage,
  907. original: Data? = nil,
  908. forKey key: String,
  909. processorIdentifier identifier: String = "",
  910. cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
  911. toDisk: Bool = true
  912. ) async throws {
  913. try await withCheckedThrowingContinuation { continuation in
  914. store(
  915. image,
  916. original: original,
  917. forKey: key,
  918. processorIdentifier: identifier,
  919. cacheSerializer: serializer,
  920. toDisk: toDisk) {
  921. // Only `diskCacheResult` can fail
  922. continuation.resume(with: $0.diskCacheResult)
  923. }
  924. }
  925. }
  926. open func storeToDisk(
  927. _ data: Data,
  928. forKey key: String,
  929. processorIdentifier identifier: String = "",
  930. expiration: StorageExpiration? = nil
  931. ) async throws
  932. {
  933. try await withCheckedThrowingContinuation { continuation in
  934. storeToDisk(
  935. data,
  936. forKey: key,
  937. processorIdentifier: identifier,
  938. expiration: expiration) {
  939. // Only `diskCacheResult` can fail
  940. continuation.resume(with: $0.diskCacheResult)
  941. }
  942. }
  943. }
  944. /// Removes the image for the given key from the cache.
  945. ///
  946. /// - Parameters:
  947. /// - key: The key used for caching the image.
  948. /// - identifier: The identifier of the processor being used for caching. If you are using a processor for the
  949. /// image, pass the identifier of the processor to this parameter.
  950. /// - fromMemory: Whether this image should be removed from memory storage or not. If `false`, the image won't be
  951. /// removed from the memory storage. The default is `true`.
  952. /// - fromDisk: Whether this image should be removed from the disk storage or not. If `false`, the image won't be
  953. /// removed from the disk storage. The default is `true`.
  954. open func removeImage(
  955. forKey key: String,
  956. processorIdentifier identifier: String = "",
  957. fromMemory: Bool = true,
  958. fromDisk: Bool = true
  959. ) async throws {
  960. return try await withCheckedThrowingContinuation { continuation in
  961. removeImage(
  962. forKey: key,
  963. processorIdentifier: identifier,
  964. fromMemory: fromMemory,
  965. fromDisk: fromDisk,
  966. completionHandler: { error in
  967. if let error {
  968. continuation.resume(throwing: error)
  969. } else {
  970. continuation.resume()
  971. }
  972. }
  973. )
  974. }
  975. }
  976. /// Retrieves an image for a given key from the cache, either from memory storage or disk storage.
  977. ///
  978. /// - Parameters:
  979. /// - key: The key used for caching the image.
  980. /// - options: The ``KingfisherParsedOptionsInfo`` options setting used for retrieving the image.
  981. /// - Returns:
  982. /// If the image retrieving operation finishes without problem, an ``ImageCacheResult`` value.
  983. ///
  984. /// - Throws: An error of type ``KingfisherError``, if any error happens inside Kingfisher framework.
  985. open func retrieveImage(
  986. forKey key: String,
  987. options: KingfisherParsedOptionsInfo
  988. ) async throws -> ImageCacheResult {
  989. try await withCheckedThrowingContinuation { continuation in
  990. retrieveImage(forKey: key, options: options) { continuation.resume(with: $0) }
  991. }
  992. }
  993. /// Retrieves an image for a given key from the cache, either from memory storage or disk storage.
  994. ///
  995. /// - Parameters:
  996. /// - key: The key used for caching the image.
  997. /// - options: The ``KingfisherOptionsInfo`` options setting used for retrieving the image.
  998. ///
  999. /// - Returns: If the image retrieving operation finishes without problem, an ``ImageCacheResult`` value.
  1000. ///
  1001. /// - Throws: An error of type ``KingfisherError``, if any error happens inside Kingfisher framework.
  1002. ///
  1003. /// > This method is marked as `open` for compatibility purposes only. Do not override this method. Instead,
  1004. /// override the version ``ImageCache/retrieveImage(forKey:options:callbackQueue:completionHandler:)-1m1bb`` that
  1005. /// accepts a ``KingfisherParsedOptionsInfo`` value.
  1006. open func retrieveImage(
  1007. forKey key: String,
  1008. options: KingfisherOptionsInfo? = nil
  1009. ) async throws -> ImageCacheResult {
  1010. try await withCheckedThrowingContinuation { continuation in
  1011. retrieveImage(forKey: key, options: options) { continuation.resume(with: $0) }
  1012. }
  1013. }
  1014. /// Retrieves an image associated with a given key from the disk storage.
  1015. ///
  1016. /// - Parameters:
  1017. /// - key: The key used for caching the image.
  1018. /// - options: The ``KingfisherOptionsInfo`` options setting used to fetch the image.
  1019. ///
  1020. /// - Returns: The image stored in the disk cache if it exists and is valid. If the image does not exist or has
  1021. /// already expired, `nil` is returned.
  1022. ///
  1023. /// - Returns: If the image retrieving operation finishes without problem, an ``ImageCacheResult`` value.
  1024. ///
  1025. /// - Throws: An error of type ``KingfisherError``, if any error happens inside Kingfisher framework.
  1026. /// ``KingfisherParsedOptionsInfo`` value.
  1027. open func retrieveImageInDiskCache(
  1028. forKey key: String,
  1029. options: KingfisherOptionsInfo? = nil
  1030. ) async throws -> KFCrossPlatformImage? {
  1031. try await withCheckedThrowingContinuation { continuation in
  1032. retrieveImageInDiskCache(forKey: key, options: options) {
  1033. continuation.resume(with: $0)
  1034. }
  1035. }
  1036. }
  1037. /// Clears the memory and disk storage of this cache.
  1038. ///
  1039. /// This is an asynchronous operation. When the cache clearing operation finishes, the whole method returns.
  1040. open func clearCache() async {
  1041. await withCheckedContinuation { continuation in
  1042. clearCache { continuation.resume() }
  1043. }
  1044. }
  1045. /// Clears the disk storage of this cache.
  1046. ///
  1047. /// This is an asynchronous operation. When the cache clearing operation finishes, the whole method returns.
  1048. open func clearDiskCache() async {
  1049. await withCheckedContinuation { continuation in
  1050. clearDiskCache { continuation.resume() }
  1051. }
  1052. }
  1053. /// Clears the expired images from the memory and disk storage.
  1054. ///
  1055. /// This is an asynchronous operation. When the cache clearing operation finishes, the whole method returns.
  1056. open func cleanExpiredCache() async {
  1057. await withCheckedContinuation { continuation in
  1058. cleanExpiredCache { continuation.resume() }
  1059. }
  1060. }
  1061. /// Clears the expired images from disk storage.
  1062. ///
  1063. /// This is an asynchronous operation. When the cache clearing operation finishes, the whole method returns.
  1064. open func cleanExpiredDiskCache() async {
  1065. await withCheckedContinuation { continuation in
  1066. cleanExpiredDiskCache { continuation.resume() }
  1067. }
  1068. }
  1069. /// Calculates the size taken by the disk storage.
  1070. ///
  1071. /// It represents the total file size of all cached files in the ``ImageCache/diskStorage`` on disk in bytes.
  1072. open var diskStorageSize: UInt {
  1073. get async throws {
  1074. try await withCheckedThrowingContinuation { continuation in
  1075. calculateDiskStorageSize { continuation.resume(with: $0) }
  1076. }
  1077. }
  1078. }
  1079. }
  1080. // Concurrency
  1081. #if !os(macOS) && !os(watchOS)
  1082. // MARK: - For App Extensions
  1083. extension UIApplication: KingfisherCompatible { }
  1084. extension KingfisherWrapper where Base: UIApplication {
  1085. public static var shared: UIApplication? {
  1086. let selector = NSSelectorFromString("sharedApplication")
  1087. guard Base.responds(to: selector) else { return nil }
  1088. return Base.perform(selector).takeUnretainedValue() as? UIApplication
  1089. }
  1090. }
  1091. #endif
  1092. extension String {
  1093. func computedKey(with identifier: String) -> String {
  1094. if identifier.isEmpty {
  1095. return self
  1096. } else {
  1097. return appending("@\(identifier)")
  1098. }
  1099. }
  1100. }