ImageCache.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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 will be sent when the disk cache got cleaned either there are cached files expired or the
  33. /// total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger
  34. /// this notification.
  35. ///
  36. /// The `object` of this notification is the `ImageCache` object which sends the notification.
  37. /// A list of removed hashes (files) could be retrieved by accessing the array under
  38. /// `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received.
  39. /// By checking the array, you could know the hash codes of files are removed.
  40. public static let KingfisherDidCleanDiskCache =
  41. Notification.Name("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache")
  42. }
  43. /// Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`.
  44. public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash"
  45. /// Cache type of a cached image.
  46. /// - none: The image is not cached yet when retrieving it.
  47. /// - memory: The image is cached in memory.
  48. /// - disk: The image is cached in disk.
  49. public enum CacheType {
  50. /// The image is not cached yet when retrieving it.
  51. case none
  52. /// The image is cached in memory.
  53. case memory
  54. /// The image is cached in disk.
  55. case disk
  56. /// Whether the cache type represents the image is already cached or not.
  57. public var cached: Bool {
  58. switch self {
  59. case .memory, .disk: return true
  60. case .none: return false
  61. }
  62. }
  63. }
  64. /// Represents the caching operation result.
  65. public struct CacheStoreResult {
  66. /// The cache result for memory cache. Caching an image to memory will never fail.
  67. public let memoryCacheResult: Result<(), Never>
  68. /// The cache result for disk cache. If an error happens during caching operation,
  69. /// you can get it from `.failure` case of this `diskCacheResult`.
  70. public let diskCacheResult: Result<(), KingfisherError>
  71. }
  72. extension KFCrossPlatformImage: CacheCostCalculable {
  73. /// Cost of an image
  74. public var cacheCost: Int { return kf.cost }
  75. }
  76. extension Data: DataTransformable {
  77. public func toData() throws -> Data {
  78. return self
  79. }
  80. public static func fromData(_ data: Data) throws -> Data {
  81. return data
  82. }
  83. public static let empty = Data()
  84. }
  85. /// Represents the getting image operation from the cache.
  86. ///
  87. /// - disk: The image can be retrieved from disk cache.
  88. /// - memory: The image can be retrieved memory cache.
  89. /// - none: The image does not exist in the cache.
  90. public enum ImageCacheResult {
  91. /// The image can be retrieved from disk cache.
  92. case disk(KFCrossPlatformImage)
  93. /// The image can be retrieved memory cache.
  94. case memory(KFCrossPlatformImage)
  95. /// The image does not exist in the cache.
  96. case none
  97. /// Extracts the image from cache result. It returns the associated `Image` value for
  98. /// `.disk` and `.memory` case. For `.none` case, `nil` is returned.
  99. public var image: KFCrossPlatformImage? {
  100. switch self {
  101. case .disk(let image): return image
  102. case .memory(let image): return image
  103. case .none: return nil
  104. }
  105. }
  106. /// Returns the corresponding `CacheType` value based on the result type of `self`.
  107. public var cacheType: CacheType {
  108. switch self {
  109. case .disk: return .disk
  110. case .memory: return .memory
  111. case .none: return .none
  112. }
  113. }
  114. }
  115. /// Represents a hybrid caching system which is composed by a `MemoryStorage.Backend` and a `DiskStorage.Backend`.
  116. /// `ImageCache` is a high level abstract for storing an image as well as its data to disk memory and disk, and
  117. /// retrieving them back.
  118. ///
  119. /// While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create
  120. /// your own cache object and configure its storages as your need. This class also provide an interface for you to set
  121. /// the memory and disk storage config.
  122. open class ImageCache {
  123. // MARK: Singleton
  124. /// The default `ImageCache` object. Kingfisher will use this cache for its related methods if there is no
  125. /// other cache specified. The `name` of this default cache is "default", and you should not use this name
  126. /// for any of your customize cache.
  127. public static let `default` = ImageCache(name: "default")
  128. // MARK: Public Properties
  129. /// The `MemoryStorage.Backend` object used in this cache. This storage holds loaded images in memory with a
  130. /// reasonable expire duration and a maximum memory usage. To modify the configuration of a storage, just set
  131. /// the storage `config` and its properties.
  132. public let memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>
  133. /// The `DiskStorage.Backend` object used in this cache. This storage stores loaded images in disk with a
  134. /// reasonable expire duration and a maximum disk usage. To modify the configuration of a storage, just set
  135. /// the storage `config` and its properties.
  136. public let diskStorage: DiskStorage.Backend<Data>
  137. private let ioQueue: DispatchQueue
  138. /// Closure that defines the disk cache path from a given path and cacheName.
  139. public typealias DiskCachePathClosure = (URL, String) -> URL
  140. // MARK: Initializers
  141. /// Creates an `ImageCache` from a customized `MemoryStorage` and `DiskStorage`.
  142. ///
  143. /// - Parameters:
  144. /// - memoryStorage: The `MemoryStorage.Backend` object to use in the image cache.
  145. /// - diskStorage: The `DiskStorage.Backend` object to use in the image cache.
  146. public init(
  147. memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>,
  148. diskStorage: DiskStorage.Backend<Data>)
  149. {
  150. self.memoryStorage = memoryStorage
  151. self.diskStorage = diskStorage
  152. let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(UUID().uuidString)"
  153. ioQueue = DispatchQueue(label: ioQueueName)
  154. let notifications: [(Notification.Name, Selector)]
  155. #if !os(macOS) && !os(watchOS)
  156. #if swift(>=4.2)
  157. notifications = [
  158. (UIApplication.didReceiveMemoryWarningNotification, #selector(clearMemoryCache)),
  159. (UIApplication.willTerminateNotification, #selector(cleanExpiredDiskCache)),
  160. (UIApplication.didEnterBackgroundNotification, #selector(backgroundCleanExpiredDiskCache))
  161. ]
  162. #else
  163. notifications = [
  164. (NSNotification.Name.UIApplicationDidReceiveMemoryWarning, #selector(clearMemoryCache)),
  165. (NSNotification.Name.UIApplicationWillTerminate, #selector(cleanExpiredDiskCache)),
  166. (NSNotification.Name.UIApplicationDidEnterBackground, #selector(backgroundCleanExpiredDiskCache))
  167. ]
  168. #endif
  169. #elseif os(macOS)
  170. notifications = [
  171. (NSApplication.willResignActiveNotification, #selector(cleanExpiredDiskCache)),
  172. ]
  173. #else
  174. notifications = []
  175. #endif
  176. notifications.forEach {
  177. NotificationCenter.default.addObserver(self, selector: $0.1, name: $0.0, object: nil)
  178. }
  179. }
  180. /// Creates an `ImageCache` with a given `name`. Both `MemoryStorage` and `DiskStorage` will be created
  181. /// with a default config based on the `name`.
  182. ///
  183. /// - Parameter name: The name of cache object. It is used to setup disk cache directories and IO queue.
  184. /// You should not use the same `name` for different caches, otherwise, the disk storage would
  185. /// be conflicting to each other. The `name` should not be an empty string.
  186. public convenience init(name: String) {
  187. self.init(noThrowName: name, cacheDirectoryURL: nil, diskCachePathClosure: nil)
  188. }
  189. /// Creates an `ImageCache` with a given `name`, cache directory `path`
  190. /// and a closure to modify the cache directory.
  191. ///
  192. /// - Parameters:
  193. /// - name: The name of cache object. It is used to setup disk cache directories and IO queue.
  194. /// You should not use the same `name` for different caches, otherwise, the disk storage would
  195. /// be conflicting to each other.
  196. /// - cacheDirectoryURL: Location of cache directory URL on disk. It will be internally pass to the
  197. /// initializer of `DiskStorage` as the disk cache directory. If `nil`, the cache
  198. /// directory under user domain mask will be used.
  199. /// - diskCachePathClosure: Closure that takes in an optional initial path string and generates
  200. /// the final disk cache path. You could use it to fully customize your cache path.
  201. /// - Throws: An error that happens during image cache creating, such as unable to create a directory at the given
  202. /// path.
  203. public convenience init(
  204. name: String,
  205. cacheDirectoryURL: URL?,
  206. diskCachePathClosure: DiskCachePathClosure? = nil
  207. ) throws
  208. {
  209. if name.isEmpty {
  210. fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
  211. }
  212. let memoryStorage = ImageCache.createMemoryStorage()
  213. let config = ImageCache.createConfig(
  214. name: name, cacheDirectoryURL: cacheDirectoryURL, diskCachePathClosure: diskCachePathClosure
  215. )
  216. let diskStorage = try DiskStorage.Backend<Data>(config: config)
  217. self.init(memoryStorage: memoryStorage, diskStorage: diskStorage)
  218. }
  219. convenience init(
  220. noThrowName name: String,
  221. cacheDirectoryURL: URL?,
  222. diskCachePathClosure: DiskCachePathClosure?
  223. )
  224. {
  225. if name.isEmpty {
  226. fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
  227. }
  228. let memoryStorage = ImageCache.createMemoryStorage()
  229. let config = ImageCache.createConfig(
  230. name: name, cacheDirectoryURL: cacheDirectoryURL, diskCachePathClosure: diskCachePathClosure
  231. )
  232. let diskStorage = DiskStorage.Backend<Data>(noThrowConfig: config, creatingDirectory: true)
  233. self.init(memoryStorage: memoryStorage, diskStorage: diskStorage)
  234. }
  235. private static func createMemoryStorage() -> MemoryStorage.Backend<KFCrossPlatformImage> {
  236. let totalMemory = ProcessInfo.processInfo.physicalMemory
  237. let costLimit = totalMemory / 4
  238. let memoryStorage = MemoryStorage.Backend<KFCrossPlatformImage>(config:
  239. .init(totalCostLimit: (costLimit > Int.max) ? Int.max : Int(costLimit)))
  240. return memoryStorage
  241. }
  242. private static func createConfig(
  243. name: String,
  244. cacheDirectoryURL: URL?,
  245. diskCachePathClosure: DiskCachePathClosure? = nil
  246. ) -> DiskStorage.Config
  247. {
  248. var diskConfig = DiskStorage.Config(
  249. name: name,
  250. sizeLimit: 0,
  251. directory: cacheDirectoryURL
  252. )
  253. if let closure = diskCachePathClosure {
  254. diskConfig.cachePathBlock = closure
  255. }
  256. return diskConfig
  257. }
  258. deinit {
  259. NotificationCenter.default.removeObserver(self)
  260. }
  261. // MARK: Storing Images
  262. open func store(_ image: KFCrossPlatformImage,
  263. original: Data? = nil,
  264. forKey key: String,
  265. options: KingfisherParsedOptionsInfo,
  266. toDisk: Bool = true,
  267. completionHandler: ((CacheStoreResult) -> Void)? = nil)
  268. {
  269. let identifier = options.processor.identifier
  270. let callbackQueue = options.callbackQueue
  271. let computedKey = key.computedKey(with: identifier)
  272. // Memory storage should not throw.
  273. memoryStorage.storeNoThrow(value: image, forKey: computedKey, expiration: options.memoryCacheExpiration)
  274. guard toDisk else {
  275. if let completionHandler = completionHandler {
  276. let result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(()))
  277. callbackQueue.execute { completionHandler(result) }
  278. }
  279. return
  280. }
  281. ioQueue.async {
  282. let serializer = options.cacheSerializer
  283. if let data = serializer.data(with: image, original: original) {
  284. self.syncStoreToDisk(
  285. data,
  286. forKey: key,
  287. processorIdentifier: identifier,
  288. callbackQueue: callbackQueue,
  289. expiration: options.diskCacheExpiration,
  290. completionHandler: completionHandler)
  291. } else {
  292. guard let completionHandler = completionHandler else { return }
  293. let diskError = KingfisherError.cacheError(
  294. reason: .cannotSerializeImage(image: image, original: original, serializer: serializer))
  295. let result = CacheStoreResult(
  296. memoryCacheResult: .success(()),
  297. diskCacheResult: .failure(diskError))
  298. callbackQueue.execute { completionHandler(result) }
  299. }
  300. }
  301. }
  302. /// Stores an image to the cache.
  303. ///
  304. /// - Parameters:
  305. /// - image: The image to be stored.
  306. /// - original: The original data of the image. This value will be forwarded to the provided `serializer` for
  307. /// further use. By default, Kingfisher uses a `DefaultCacheSerializer` to serialize the image to
  308. /// data for caching in disk, it checks the image format based on `original` data to determine in
  309. /// which image format should be used. For other types of `serializer`, it depends on their
  310. /// implementation detail on how to use this original data.
  311. /// - key: The key used for caching the image.
  312. /// - identifier: The identifier of processor being used for caching. If you are using a processor for the
  313. /// image, pass the identifier of processor to this parameter.
  314. /// - serializer: The `CacheSerializer`
  315. /// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory.
  316. /// Otherwise, it is cached in both memory storage and disk storage. Default is `true`.
  317. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. For case
  318. /// that `toDisk` is `false`, a `.untouch` queue means `callbackQueue` will be invoked from the
  319. /// caller queue of this method. If `toDisk` is `true`, the `completionHandler` will be called
  320. /// from an internal file IO queue. To change this behavior, specify another `CallbackQueue`
  321. /// value.
  322. /// - completionHandler: A closure which is invoked when the cache operation finishes.
  323. open func store(_ image: KFCrossPlatformImage,
  324. original: Data? = nil,
  325. forKey key: String,
  326. processorIdentifier identifier: String = "",
  327. cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
  328. toDisk: Bool = true,
  329. callbackQueue: CallbackQueue = .untouch,
  330. completionHandler: ((CacheStoreResult) -> Void)? = nil)
  331. {
  332. struct TempProcessor: ImageProcessor {
  333. let identifier: String
  334. func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  335. return nil
  336. }
  337. }
  338. let options = KingfisherParsedOptionsInfo([
  339. .processor(TempProcessor(identifier: identifier)),
  340. .cacheSerializer(serializer),
  341. .callbackQueue(callbackQueue)
  342. ])
  343. store(image, original: original, forKey: key, options: options,
  344. toDisk: toDisk, completionHandler: completionHandler)
  345. }
  346. open func storeToDisk(
  347. _ data: Data,
  348. forKey key: String,
  349. processorIdentifier identifier: String = "",
  350. expiration: StorageExpiration? = nil,
  351. callbackQueue: CallbackQueue = .untouch,
  352. completionHandler: ((CacheStoreResult) -> Void)? = nil)
  353. {
  354. ioQueue.async {
  355. self.syncStoreToDisk(
  356. data,
  357. forKey: key,
  358. processorIdentifier: identifier,
  359. callbackQueue: callbackQueue,
  360. expiration: expiration,
  361. completionHandler: completionHandler)
  362. }
  363. }
  364. private func syncStoreToDisk(
  365. _ data: Data,
  366. forKey key: String,
  367. processorIdentifier identifier: String = "",
  368. callbackQueue: CallbackQueue = .untouch,
  369. expiration: StorageExpiration? = nil,
  370. completionHandler: ((CacheStoreResult) -> Void)? = nil)
  371. {
  372. let computedKey = key.computedKey(with: identifier)
  373. let result: CacheStoreResult
  374. do {
  375. try self.diskStorage.store(value: data, forKey: computedKey, expiration: expiration)
  376. result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(()))
  377. } catch {
  378. let diskError: KingfisherError
  379. if let error = error as? KingfisherError {
  380. diskError = error
  381. } else {
  382. diskError = .cacheError(reason: .cannotConvertToData(object: data, error: error))
  383. }
  384. result = CacheStoreResult(
  385. memoryCacheResult: .success(()),
  386. diskCacheResult: .failure(diskError)
  387. )
  388. }
  389. if let completionHandler = completionHandler {
  390. callbackQueue.execute { completionHandler(result) }
  391. }
  392. }
  393. // MARK: Removing Images
  394. /// Removes the image for the given key from the cache.
  395. ///
  396. /// - Parameters:
  397. /// - key: The key used for caching the image.
  398. /// - identifier: The identifier of processor being used for caching. If you are using a processor for the
  399. /// image, pass the identifier of processor to this parameter.
  400. /// - fromMemory: Whether this image should be removed from memory storage or not.
  401. /// If `false`, the image won't be removed from the memory storage. Default is `true`.
  402. /// - fromDisk: Whether this image should be removed from disk storage or not.
  403. /// If `false`, the image won't be removed from the disk storage. Default is `true`.
  404. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`.
  405. /// - completionHandler: A closure which is invoked when the cache removing operation finishes.
  406. open func removeImage(forKey key: String,
  407. processorIdentifier identifier: String = "",
  408. fromMemory: Bool = true,
  409. fromDisk: Bool = true,
  410. callbackQueue: CallbackQueue = .untouch,
  411. completionHandler: (() -> Void)? = nil)
  412. {
  413. let computedKey = key.computedKey(with: identifier)
  414. if fromMemory {
  415. memoryStorage.remove(forKey: computedKey)
  416. }
  417. if fromDisk {
  418. ioQueue.async{
  419. try? self.diskStorage.remove(forKey: computedKey)
  420. if let completionHandler = completionHandler {
  421. callbackQueue.execute { completionHandler() }
  422. }
  423. }
  424. } else {
  425. if let completionHandler = completionHandler {
  426. callbackQueue.execute { completionHandler() }
  427. }
  428. }
  429. }
  430. func retrieveImage(forKey key: String,
  431. options: KingfisherParsedOptionsInfo,
  432. callbackQueue: CallbackQueue = .mainCurrentOrAsync,
  433. completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?)
  434. {
  435. // No completion handler. No need to start working and early return.
  436. guard let completionHandler = completionHandler else { return }
  437. // Try to check the image from memory cache first.
  438. if let image = retrieveImageInMemoryCache(forKey: key, options: options) {
  439. callbackQueue.execute { completionHandler(.success(.memory(image))) }
  440. } else if options.fromMemoryCacheOrRefresh {
  441. callbackQueue.execute { completionHandler(.success(.none)) }
  442. } else {
  443. // Begin to disk search.
  444. self.retrieveImageInDiskCache(forKey: key, options: options, callbackQueue: callbackQueue) {
  445. result in
  446. switch result {
  447. case .success(let image):
  448. guard let image = image else {
  449. // No image found in disk storage.
  450. callbackQueue.execute { completionHandler(.success(.none)) }
  451. return
  452. }
  453. // Cache the disk image to memory.
  454. // We are passing `false` to `toDisk`, the memory cache does not change
  455. // callback queue, we can call `completionHandler` without another dispatch.
  456. var cacheOptions = options
  457. cacheOptions.callbackQueue = .untouch
  458. self.store(
  459. image,
  460. forKey: key,
  461. options: cacheOptions,
  462. toDisk: false)
  463. {
  464. _ in
  465. callbackQueue.execute { completionHandler(.success(.disk(image))) }
  466. }
  467. case .failure(let error):
  468. callbackQueue.execute { completionHandler(.failure(error)) }
  469. }
  470. }
  471. }
  472. }
  473. // MARK: Getting Images
  474. /// Gets an image for a given key from the cache, either from memory storage or disk storage.
  475. ///
  476. /// - Parameters:
  477. /// - key: The key used for caching the image.
  478. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image.
  479. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.mainCurrentOrAsync`.
  480. /// - completionHandler: A closure which is invoked when the image getting operation finishes. If the
  481. /// image retrieving operation finishes without problem, an `ImageCacheResult` value
  482. /// will be sent to this closure as result. Otherwise, a `KingfisherError` result
  483. /// with detail failing reason will be sent.
  484. open func retrieveImage(forKey key: String,
  485. options: KingfisherOptionsInfo? = nil,
  486. callbackQueue: CallbackQueue = .mainCurrentOrAsync,
  487. completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?)
  488. {
  489. retrieveImage(
  490. forKey: key,
  491. options: KingfisherParsedOptionsInfo(options),
  492. callbackQueue: callbackQueue,
  493. completionHandler: completionHandler)
  494. }
  495. func retrieveImageInMemoryCache(
  496. forKey key: String,
  497. options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?
  498. {
  499. let computedKey = key.computedKey(with: options.processor.identifier)
  500. return memoryStorage.value(forKey: computedKey, extendingExpiration: options.memoryCacheAccessExtendingExpiration)
  501. }
  502. /// Gets an image for a given key from the memory storage.
  503. ///
  504. /// - Parameters:
  505. /// - key: The key used for caching the image.
  506. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image.
  507. /// - Returns: The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or
  508. /// has already expired, `nil` is returned.
  509. open func retrieveImageInMemoryCache(
  510. forKey key: String,
  511. options: KingfisherOptionsInfo? = nil) -> KFCrossPlatformImage?
  512. {
  513. return retrieveImageInMemoryCache(forKey: key, options: KingfisherParsedOptionsInfo(options))
  514. }
  515. func retrieveImageInDiskCache(
  516. forKey key: String,
  517. options: KingfisherParsedOptionsInfo,
  518. callbackQueue: CallbackQueue = .untouch,
  519. completionHandler: @escaping (Result<KFCrossPlatformImage?, KingfisherError>) -> Void)
  520. {
  521. let computedKey = key.computedKey(with: options.processor.identifier)
  522. let loadingQueue: CallbackQueue = options.loadDiskFileSynchronously ? .untouch : .dispatch(ioQueue)
  523. loadingQueue.execute {
  524. do {
  525. var image: KFCrossPlatformImage? = nil
  526. if let data = try self.diskStorage.value(forKey: computedKey, extendingExpiration: options.diskCacheAccessExtendingExpiration) {
  527. image = options.cacheSerializer.image(with: data, options: options)
  528. }
  529. callbackQueue.execute { completionHandler(.success(image)) }
  530. } catch {
  531. if let error = error as? KingfisherError {
  532. callbackQueue.execute { completionHandler(.failure(error)) }
  533. } else {
  534. assertionFailure("The internal thrown error should be a `KingfisherError`.")
  535. }
  536. }
  537. }
  538. }
  539. /// Gets an image for a given key from the disk storage.
  540. ///
  541. /// - Parameters:
  542. /// - key: The key used for caching the image.
  543. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image.
  544. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`.
  545. /// - completionHandler: A closure which is invoked when the operation finishes.
  546. open func retrieveImageInDiskCache(
  547. forKey key: String,
  548. options: KingfisherOptionsInfo? = nil,
  549. callbackQueue: CallbackQueue = .untouch,
  550. completionHandler: @escaping (Result<KFCrossPlatformImage?, KingfisherError>) -> Void)
  551. {
  552. retrieveImageInDiskCache(
  553. forKey: key,
  554. options: KingfisherParsedOptionsInfo(options),
  555. callbackQueue: callbackQueue,
  556. completionHandler: completionHandler)
  557. }
  558. // MARK: Cleaning
  559. /// Clears the memory & disk storage of this cache. This is an async operation.
  560. ///
  561. /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes.
  562. /// This `handler` will be called from the main queue.
  563. public func clearCache(completion handler: (() -> Void)? = nil) {
  564. clearMemoryCache()
  565. clearDiskCache(completion: handler)
  566. }
  567. /// Clears the memory storage of this cache.
  568. @objc public func clearMemoryCache() {
  569. memoryStorage.removeAll()
  570. }
  571. /// Clears the disk storage of this cache. This is an async operation.
  572. ///
  573. /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes.
  574. /// This `handler` will be called from the main queue.
  575. open func clearDiskCache(completion handler: (() -> Void)? = nil) {
  576. ioQueue.async {
  577. do {
  578. try self.diskStorage.removeAll()
  579. } catch _ { }
  580. if let handler = handler {
  581. DispatchQueue.main.async { handler() }
  582. }
  583. }
  584. }
  585. /// Clears the expired images from memory & disk storage. This is an async operation.
  586. open func cleanExpiredCache(completion handler: (() -> Void)? = nil) {
  587. cleanExpiredMemoryCache()
  588. cleanExpiredDiskCache(completion: handler)
  589. }
  590. /// Clears the expired images from disk storage.
  591. open func cleanExpiredMemoryCache() {
  592. memoryStorage.removeExpired()
  593. }
  594. /// Clears the expired images from disk storage. This is an async operation.
  595. @objc func cleanExpiredDiskCache() {
  596. cleanExpiredDiskCache(completion: nil)
  597. }
  598. /// Clears the expired images from disk storage. This is an async operation.
  599. ///
  600. /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes.
  601. /// This `handler` will be called from the main queue.
  602. open func cleanExpiredDiskCache(completion handler: (() -> Void)? = nil) {
  603. ioQueue.async {
  604. do {
  605. var removed: [URL] = []
  606. let removedExpired = try self.diskStorage.removeExpiredValues()
  607. removed.append(contentsOf: removedExpired)
  608. let removedSizeExceeded = try self.diskStorage.removeSizeExceededValues()
  609. removed.append(contentsOf: removedSizeExceeded)
  610. if !removed.isEmpty {
  611. DispatchQueue.main.async {
  612. let cleanedHashes = removed.map { $0.lastPathComponent }
  613. NotificationCenter.default.post(
  614. name: .KingfisherDidCleanDiskCache,
  615. object: self,
  616. userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
  617. }
  618. }
  619. if let handler = handler {
  620. DispatchQueue.main.async { handler() }
  621. }
  622. } catch {}
  623. }
  624. }
  625. #if !os(macOS) && !os(watchOS)
  626. /// Clears the expired images from disk storage when app is in background. This is an async operation.
  627. /// In most cases, you should not call this method explicitly.
  628. /// It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
  629. @objc public func backgroundCleanExpiredDiskCache() {
  630. // if 'sharedApplication()' is unavailable, then return
  631. guard let sharedApplication = KingfisherWrapper<UIApplication>.shared else { return }
  632. func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) {
  633. sharedApplication.endBackgroundTask(task)
  634. #if swift(>=4.2)
  635. task = UIBackgroundTaskIdentifier.invalid
  636. #else
  637. task = UIBackgroundTaskInvalid
  638. #endif
  639. }
  640. var backgroundTask: UIBackgroundTaskIdentifier!
  641. backgroundTask = sharedApplication.beginBackgroundTask {
  642. endBackgroundTask(&backgroundTask!)
  643. }
  644. cleanExpiredDiskCache {
  645. endBackgroundTask(&backgroundTask!)
  646. }
  647. }
  648. #endif
  649. // MARK: Image Cache State
  650. /// Returns the cache type for a given `key` and `identifier` combination.
  651. /// This method is used for checking whether an image is cached in current cache.
  652. /// It also provides information on which kind of cache can it be found in the return value.
  653. ///
  654. /// - Parameters:
  655. /// - key: The key used for caching the image.
  656. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of
  657. /// `DefaultImageProcessor.default`.
  658. /// - Returns: A `CacheType` instance which indicates the cache status.
  659. /// `.none` means the image is not in cache or it is already expired.
  660. open func imageCachedType(
  661. forKey key: String,
  662. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> CacheType
  663. {
  664. let computedKey = key.computedKey(with: identifier)
  665. if memoryStorage.isCached(forKey: computedKey) { return .memory }
  666. if diskStorage.isCached(forKey: computedKey) { return .disk }
  667. return .none
  668. }
  669. /// Returns whether the file exists in cache for a given `key` and `identifier` combination.
  670. ///
  671. /// - Parameters:
  672. /// - key: The key used for caching the image.
  673. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of
  674. /// `DefaultImageProcessor.default`.
  675. /// - Returns: A `Bool` which indicates whether a cache could match the given `key` and `identifier` combination.
  676. ///
  677. /// - Note:
  678. /// The return value does not contain information about from which kind of storage the cache matches.
  679. /// To get the information about cache type according `CacheType`,
  680. /// use `imageCachedType(forKey:processorIdentifier:)` instead.
  681. public func isCached(
  682. forKey key: String,
  683. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> Bool
  684. {
  685. return imageCachedType(forKey: key, processorIdentifier: identifier).cached
  686. }
  687. /// Gets the hash used as cache file name for the key.
  688. ///
  689. /// - Parameters:
  690. /// - key: The key used for caching the image.
  691. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of
  692. /// `DefaultImageProcessor.default`.
  693. /// - Returns: The hash which is used as the cache file name.
  694. ///
  695. /// - Note:
  696. /// By default, for a given combination of `key` and `identifier`, `ImageCache` will use the value
  697. /// returned by this method as the cache file name. You can use this value to check and match cache file
  698. /// if you need.
  699. open func hash(
  700. forKey key: String,
  701. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
  702. {
  703. let computedKey = key.computedKey(with: identifier)
  704. return diskStorage.cacheFileName(forKey: computedKey)
  705. }
  706. /// Calculates the size taken by the disk storage.
  707. /// It is the total file size of all cached files in the `diskStorage` on disk in bytes.
  708. ///
  709. /// - Parameter handler: Called with the size calculating finishes. This closure is invoked from the main queue.
  710. open func calculateDiskStorageSize(completion handler: @escaping ((Result<UInt, KingfisherError>) -> Void)) {
  711. ioQueue.async {
  712. do {
  713. let size = try self.diskStorage.totalSize()
  714. DispatchQueue.main.async { handler(.success(size)) }
  715. } catch {
  716. if let error = error as? KingfisherError {
  717. DispatchQueue.main.async { handler(.failure(error)) }
  718. } else {
  719. assertionFailure("The internal thrown error should be a `KingfisherError`.")
  720. }
  721. }
  722. }
  723. }
  724. /// Gets the cache path for the key.
  725. /// It is useful for projects with web view or anyone that needs access to the local file path.
  726. ///
  727. /// i.e. Replacing the `<img src='path_for_key'>` tag in your HTML.
  728. ///
  729. /// - Parameters:
  730. /// - key: The key used for caching the image.
  731. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of
  732. /// `DefaultImageProcessor.default`.
  733. /// - Returns: The disk path of cached image under the given `key` and `identifier`.
  734. ///
  735. /// - Note:
  736. /// This method does not guarantee there is an image already cached in the returned path. It just gives your
  737. /// the path that the image should be, if it exists in disk storage.
  738. ///
  739. /// You could use `isCached(forKey:)` method to check whether the image is cached under that key in disk.
  740. open func cachePath(
  741. forKey key: String,
  742. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
  743. {
  744. let computedKey = key.computedKey(with: identifier)
  745. return diskStorage.cacheFileURL(forKey: computedKey).path
  746. }
  747. }
  748. extension Dictionary {
  749. func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] {
  750. return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 }
  751. }
  752. }
  753. #if !os(macOS) && !os(watchOS)
  754. // MARK: - For App Extensions
  755. extension UIApplication: KingfisherCompatible { }
  756. extension KingfisherWrapper where Base: UIApplication {
  757. public static var shared: UIApplication? {
  758. let selector = NSSelectorFromString("sharedApplication")
  759. guard Base.responds(to: selector) else { return nil }
  760. return Base.perform(selector).takeUnretainedValue() as? UIApplication
  761. }
  762. }
  763. #endif
  764. extension String {
  765. func computedKey(with identifier: String) -> String {
  766. if identifier.isEmpty {
  767. return self
  768. } else {
  769. return appending("@\(identifier)")
  770. }
  771. }
  772. }