ImageCache.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. //
  2. // ImageCache.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  6. //
  7. // Copyright (c) 2018 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 Image: 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(Image)
  93. /// The image can be retrieved memory cache.
  94. case memory(Image)
  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: Image? {
  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<Image>
  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<Image>,
  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. #if !os(macOS) && !os(watchOS)
  155. #if swift(>=4.2)
  156. let notifications: [(Notification.Name, Selector)] = [
  157. (UIApplication.didReceiveMemoryWarningNotification, #selector(clearMemoryCache)),
  158. (UIApplication.willTerminateNotification, #selector(cleanExpiredDiskCache)),
  159. (UIApplication.didEnterBackgroundNotification, #selector(backgroundCleanExpiredDiskCache))
  160. ]
  161. #else
  162. let notifications: [(Notification.Name, Selector)] = [
  163. (NSNotification.Name.UIApplicationDidReceiveMemoryWarning, #selector(clearMemoryCache)),
  164. (NSNotification.Name.UIApplicationWillTerminate, #selector(cleanExpiredDiskCache)),
  165. (NSNotification.Name.UIApplicationDidEnterBackground, #selector(backgroundCleanExpiredDiskCache))
  166. ]
  167. #endif
  168. notifications.forEach {
  169. NotificationCenter.default.addObserver(self, selector: $0.1, name: $0.0, object: nil)
  170. }
  171. #endif
  172. }
  173. /// Creates an `ImageCache` with a given `name`. Both `MemoryStorage` and `DiskStorage` will be created
  174. /// with a default config based on the `name`.
  175. ///
  176. /// - Parameter name: The name of cache object. It is used to setup disk cache directories and IO queue.
  177. /// You should not use the same `name` for different caches, otherwise, the disk storage would
  178. /// be conflicting to each other. The `name` should not be an empty string.
  179. public convenience init(name: String) {
  180. try! self.init(name: name, path: nil, diskCachePathClosure: nil)
  181. }
  182. /// Creates an `ImageCache` with a given `name`, cache directory `path`
  183. /// and a closure to modify the cache directory.
  184. ///
  185. /// - Parameters:
  186. /// - name: The name of cache object. It is used to setup disk cache directories and IO queue.
  187. /// You should not use the same `name` for different caches, otherwise, the disk storage would
  188. /// be conflicting to each other.
  189. /// - path: Location of cache path on disk. It will be internally pass to the initializer of `DiskStorage` as the
  190. /// disk cache directory.
  191. /// - diskCachePathClosure: Closure that takes in an optional initial path string and generates
  192. /// the final disk cache path. You could use it to fully customize your cache path.
  193. /// - Throws: An error that happens during image cache creating, such as unable to create a directory at the given
  194. /// path.
  195. public convenience init(
  196. name: String,
  197. path: String?,
  198. diskCachePathClosure: DiskCachePathClosure? = nil) throws
  199. {
  200. if name.isEmpty {
  201. fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
  202. }
  203. let totalMemory = ProcessInfo.processInfo.physicalMemory
  204. let costLimit = totalMemory / 4
  205. let memoryStorage = MemoryStorage.Backend<Image>(config:
  206. .init(totalCostLimit: (costLimit > Int.max) ? Int.max : Int(costLimit)))
  207. var diskConfig = DiskStorage.Config(
  208. name: name,
  209. sizeLimit: 0,
  210. directory: path.flatMap { URL(string: $0) }
  211. )
  212. if let closure = diskCachePathClosure {
  213. diskConfig.cachePathBlock = closure
  214. }
  215. let diskStorage = try DiskStorage.Backend<Data>(config: diskConfig)
  216. diskConfig.cachePathBlock = nil
  217. self.init(memoryStorage: memoryStorage, diskStorage: diskStorage)
  218. }
  219. deinit {
  220. NotificationCenter.default.removeObserver(self)
  221. }
  222. // MARK: Storing Images
  223. open func store(_ image: Image,
  224. original: Data? = nil,
  225. forKey key: String,
  226. options: KingfisherParsedOptionsInfo,
  227. toDisk: Bool = true,
  228. completionHandler: ((CacheStoreResult) -> Void)? = nil)
  229. {
  230. let identifier = options.processor.identifier
  231. let callbackQueue = options.callbackQueue
  232. let computedKey = key.computedKey(with: identifier)
  233. // Memory storage should not throw.
  234. memoryStorage.storeNoThrow(value: image, forKey: computedKey, expiration: options.memoryCacheExpiration)
  235. guard toDisk else {
  236. if let completionHandler = completionHandler {
  237. let result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(()))
  238. callbackQueue.execute { completionHandler(result) }
  239. }
  240. return
  241. }
  242. ioQueue.async {
  243. let serializer = options.cacheSerializer
  244. if let data = serializer.data(with: image, original: original) {
  245. self.syncStoreToDisk(
  246. data,
  247. forKey: key,
  248. processorIdentifier: identifier,
  249. callbackQueue: callbackQueue,
  250. expiration: options.diskCacheExpiration,
  251. completionHandler: completionHandler)
  252. } else {
  253. guard let completionHandler = completionHandler else { return }
  254. let diskError = KingfisherError.cacheError(
  255. reason: .cannotSerializeImage(image: image, original: original, serializer: serializer))
  256. let result = CacheStoreResult(
  257. memoryCacheResult: .success(()),
  258. diskCacheResult: .failure(diskError))
  259. callbackQueue.execute { completionHandler(result) }
  260. }
  261. }
  262. }
  263. /// Stores an image to the cache.
  264. ///
  265. /// - Parameters:
  266. /// - image: The image to be stored.
  267. /// - original: The original data of the image. This value will be forwarded to the provided `serializer` for
  268. /// further use. By default, Kingfisher uses a `DefaultCacheSerializer` to serialize the image to
  269. /// data for caching in disk, it checks the image format based on `original` data to determine in
  270. /// which image format should be used. For other types of `serializer`, it depends on their
  271. /// implementation detail on how to use this original data.
  272. /// - key: The key used for caching the image.
  273. /// - identifier: The identifier of processor being used for caching. If you are using a processor for the
  274. /// image, pass the identifier of processor to this parameter.
  275. /// - serializer: The `CacheSerializer`
  276. /// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory.
  277. /// Otherwise, it is cached in both memory storage and disk storage. Default is `true`.
  278. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. For case
  279. /// that `toDisk` is `false`, a `.untouch` queue means `callbackQueue` will be invoked from the
  280. /// caller queue of this method. If `toDisk` is `true`, the `completionHandler` will be called
  281. /// from an internal file IO queue. To change this behavior, specify another `CallbackQueue`
  282. /// value.
  283. /// - completionHandler: A closure which is invoked when the cache operation finishes.
  284. open func store(_ image: Image,
  285. original: Data? = nil,
  286. forKey key: String,
  287. processorIdentifier identifier: String = "",
  288. cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
  289. toDisk: Bool = true,
  290. callbackQueue: CallbackQueue = .untouch,
  291. completionHandler: ((CacheStoreResult) -> Void)? = nil)
  292. {
  293. struct TempProcessor: ImageProcessor {
  294. let identifier: String
  295. func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
  296. return nil
  297. }
  298. }
  299. let options = KingfisherParsedOptionsInfo([
  300. .processor(TempProcessor(identifier: identifier)),
  301. .cacheSerializer(serializer),
  302. .callbackQueue(callbackQueue)
  303. ])
  304. store(image, original: original, forKey: key, options: options,
  305. toDisk: toDisk, completionHandler: completionHandler)
  306. }
  307. open func storeToDisk(
  308. _ data: Data,
  309. forKey key: String,
  310. processorIdentifier identifier: String = "",
  311. expiration: StorageExpiration? = nil,
  312. callbackQueue: CallbackQueue = .untouch,
  313. completionHandler: ((CacheStoreResult) -> Void)? = nil)
  314. {
  315. ioQueue.async {
  316. self.syncStoreToDisk(
  317. data,
  318. forKey: key,
  319. processorIdentifier: identifier,
  320. callbackQueue: callbackQueue,
  321. expiration: expiration,
  322. completionHandler: completionHandler)
  323. }
  324. }
  325. private func syncStoreToDisk(
  326. _ data: Data,
  327. forKey key: String,
  328. processorIdentifier identifier: String = "",
  329. callbackQueue: CallbackQueue = .untouch,
  330. expiration: StorageExpiration? = nil,
  331. completionHandler: ((CacheStoreResult) -> Void)? = nil)
  332. {
  333. let computedKey = key.computedKey(with: identifier)
  334. let result: CacheStoreResult
  335. do {
  336. try self.diskStorage.store(value: data, forKey: computedKey, expiration: expiration)
  337. result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(()))
  338. } catch {
  339. let diskError: KingfisherError
  340. if let error = error as? KingfisherError {
  341. diskError = error
  342. } else {
  343. diskError = .cacheError(reason: .cannotConvertToData(object: data, error: error))
  344. }
  345. result = CacheStoreResult(
  346. memoryCacheResult: .success(()),
  347. diskCacheResult: .failure(diskError)
  348. )
  349. }
  350. if let completionHandler = completionHandler {
  351. callbackQueue.execute { completionHandler(result) }
  352. }
  353. }
  354. // MARK: Removing Images
  355. /// Removes the image for the given key from the cache.
  356. ///
  357. /// - Parameters:
  358. /// - key: The key used for caching the image.
  359. /// - identifier: The identifier of processor being used for caching. If you are using a processor for the
  360. /// image, pass the identifier of processor to this parameter.
  361. /// - fromMemory: Whether this image should be removed from memory storage or not.
  362. /// If `false`, the image won't be removed from the memory storage. Default is `true`.
  363. /// - fromDisk: Whether this image should be removed from disk storage or not.
  364. /// If `false`, the image won't be removed from the disk storage. Default is `true`.
  365. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`.
  366. /// - completionHandler: A closure which is invoked when the cache removing operation finishes.
  367. open func removeImage(forKey key: String,
  368. processorIdentifier identifier: String = "",
  369. fromMemory: Bool = true,
  370. fromDisk: Bool = true,
  371. callbackQueue: CallbackQueue = .untouch,
  372. completionHandler: (() -> Void)? = nil)
  373. {
  374. let computedKey = key.computedKey(with: identifier)
  375. if fromMemory {
  376. try? memoryStorage.remove(forKey: computedKey)
  377. }
  378. if fromDisk {
  379. ioQueue.async{
  380. try? self.diskStorage.remove(forKey: computedKey)
  381. if let completionHandler = completionHandler {
  382. callbackQueue.execute { completionHandler() }
  383. }
  384. }
  385. } else {
  386. if let completionHandler = completionHandler {
  387. callbackQueue.execute { completionHandler() }
  388. }
  389. }
  390. }
  391. func retrieveImage(forKey key: String,
  392. options: KingfisherParsedOptionsInfo,
  393. callbackQueue: CallbackQueue = .untouch,
  394. completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?)
  395. {
  396. // No completion handler. No need to start working and early return.
  397. guard let completionHandler = completionHandler else { return }
  398. // Try to check the image from memory cache first.
  399. if let image = retrieveImageInMemoryCache(forKey: key, options: options) {
  400. let image = options.imageModifier?.modify(image) ?? image
  401. callbackQueue.execute { completionHandler(.success(.memory(image))) }
  402. } else if options.fromMemoryCacheOrRefresh {
  403. callbackQueue.execute { completionHandler(.success(.none)) }
  404. } else {
  405. // Begin to disk search.
  406. self.retrieveImageInDiskCache(forKey: key, options: options, callbackQueue: callbackQueue) {
  407. result in
  408. // The callback queue is already correct in this closure.
  409. switch result {
  410. case .success(let image):
  411. guard let image = image else {
  412. // No image found in disk storage.
  413. completionHandler(.success(.none))
  414. return
  415. }
  416. let finalImage = options.imageModifier?.modify(image) ?? image
  417. // Cache the disk image to memory.
  418. // We are passing `false` to `toDisk`, the memory cache does not change
  419. // callback queue, we can call `completionHandler` without another dispatch.
  420. var cacheOptions = options
  421. cacheOptions.callbackQueue = .untouch
  422. self.store(
  423. finalImage,
  424. forKey: key,
  425. options: cacheOptions,
  426. toDisk: false)
  427. {
  428. _ in
  429. completionHandler(.success(.disk(finalImage)))
  430. }
  431. case .failure(let error):
  432. completionHandler(.failure(error))
  433. }
  434. }
  435. }
  436. }
  437. // MARK: Getting Images
  438. /// Gets an image for a given key from the cache, either from memory storage or disk storage.
  439. ///
  440. /// - Parameters:
  441. /// - key: The key used for caching the image.
  442. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image.
  443. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`.
  444. /// - completionHandler: A closure which is invoked when the image getting operation finishes. If the
  445. /// image retrieving operation finishes without problem, an `ImageCacheResult` value
  446. /// will be sent to this closure as result. Otherwise, a `KingfisherError` result
  447. /// with detail failing reason will be sent.
  448. open func retrieveImage(forKey key: String,
  449. options: KingfisherOptionsInfo? = nil,
  450. callbackQueue: CallbackQueue = .untouch,
  451. completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?)
  452. {
  453. retrieveImage(
  454. forKey: key,
  455. options: KingfisherParsedOptionsInfo(options),
  456. callbackQueue: callbackQueue,
  457. completionHandler: completionHandler)
  458. }
  459. func retrieveImageInMemoryCache(
  460. forKey key: String,
  461. options: KingfisherParsedOptionsInfo) -> Image?
  462. {
  463. let computedKey = key.computedKey(with: options.processor.identifier)
  464. do {
  465. return try memoryStorage.value(forKey: computedKey)
  466. } catch {
  467. return nil
  468. }
  469. }
  470. /// Gets an image for a given key from the memory storage.
  471. ///
  472. /// - Parameters:
  473. /// - key: The key used for caching the image.
  474. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image.
  475. /// - Returns: The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or
  476. /// has already expired, `nil` is returned.
  477. open func retrieveImageInMemoryCache(
  478. forKey key: String,
  479. options: KingfisherOptionsInfo? = nil) -> Image?
  480. {
  481. return retrieveImageInMemoryCache(forKey: key, options: KingfisherParsedOptionsInfo(options))
  482. }
  483. func retrieveImageInDiskCache(
  484. forKey key: String,
  485. options: KingfisherParsedOptionsInfo,
  486. callbackQueue: CallbackQueue = .untouch,
  487. completionHandler: @escaping (Result<Image?, KingfisherError>) -> Void)
  488. {
  489. let computedKey = key.computedKey(with: options.processor.identifier)
  490. let loadingQueue: CallbackQueue = options.loadDiskFileSynchronously ? .untouch : .dispatch(ioQueue)
  491. loadingQueue.execute {
  492. do {
  493. var image: Image? = nil
  494. if let data = try self.diskStorage.value(forKey: computedKey) {
  495. image = options.cacheSerializer.image(with: data, options: options)
  496. }
  497. callbackQueue.execute { completionHandler(.success(image)) }
  498. } catch {
  499. if let error = error as? KingfisherError {
  500. callbackQueue.execute { completionHandler(.failure(error)) }
  501. } else {
  502. assertionFailure("The internal thrown error should be a `KingfisherError`.")
  503. }
  504. }
  505. }
  506. }
  507. /// Gets an image for a given key from the disk storage.
  508. ///
  509. /// - Parameters:
  510. /// - key: The key used for caching the image.
  511. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image.
  512. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`.
  513. /// - completionHandler: A closure which is invoked when the operation finishes.
  514. open func retrieveImageInDiskCache(
  515. forKey key: String,
  516. options: KingfisherOptionsInfo? = nil,
  517. callbackQueue: CallbackQueue = .untouch,
  518. completionHandler: @escaping (Result<Image?, KingfisherError>) -> Void)
  519. {
  520. retrieveImageInDiskCache(
  521. forKey: key,
  522. options: KingfisherParsedOptionsInfo(options),
  523. callbackQueue: callbackQueue,
  524. completionHandler: completionHandler)
  525. }
  526. // MARK: Cleaning
  527. /// Clears the memory storage of this cache.
  528. @objc public func clearMemoryCache() {
  529. try? memoryStorage.removeAll()
  530. }
  531. /// Clears the disk storage of this cache. This is an async operation.
  532. ///
  533. /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes.
  534. /// This `handler` will be called from the main queue.
  535. open func clearDiskCache(completion handler: (()->())? = nil) {
  536. ioQueue.async {
  537. do {
  538. try self.diskStorage.removeAll()
  539. } catch _ { }
  540. if let handler = handler {
  541. DispatchQueue.main.async { handler() }
  542. }
  543. }
  544. }
  545. /// Clears the expired images from disk storage. This is an async operation.
  546. open func cleanExpiredMemoryCache() {
  547. memoryStorage.removeExpired()
  548. }
  549. /// Clears the expired images from disk storage. This is an async operation.
  550. @objc func cleanExpiredDiskCache() {
  551. cleanExpiredDiskCache(completion: nil)
  552. }
  553. /// Clears the expired images from disk storage. This is an async operation.
  554. ///
  555. /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes.
  556. /// This `handler` will be called from the main queue.
  557. open func cleanExpiredDiskCache(completion handler: (() -> Void)? = nil) {
  558. ioQueue.async {
  559. do {
  560. var removed: [URL] = []
  561. let removedExpired = try self.diskStorage.removeExpiredValues()
  562. removed.append(contentsOf: removedExpired)
  563. let removedSizeExceeded = try self.diskStorage.removeSizeExceededValues()
  564. removed.append(contentsOf: removedSizeExceeded)
  565. if !removed.isEmpty {
  566. DispatchQueue.main.async {
  567. let cleanedHashes = removed.map { $0.lastPathComponent }
  568. NotificationCenter.default.post(
  569. name: .KingfisherDidCleanDiskCache,
  570. object: self,
  571. userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
  572. }
  573. }
  574. if let handler = handler {
  575. DispatchQueue.main.async { handler() }
  576. }
  577. } catch {}
  578. }
  579. }
  580. #if !os(macOS) && !os(watchOS)
  581. /// Clears the expired images from disk storage when app is in background. This is an async operation.
  582. /// In most cases, you should not call this method explicitly.
  583. /// It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
  584. @objc public func backgroundCleanExpiredDiskCache() {
  585. // if 'sharedApplication()' is unavailable, then return
  586. guard let sharedApplication = KingfisherWrapper<UIApplication>.shared else { return }
  587. func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) {
  588. sharedApplication.endBackgroundTask(task)
  589. #if swift(>=4.2)
  590. task = UIBackgroundTaskIdentifier.invalid
  591. #else
  592. task = UIBackgroundTaskInvalid
  593. #endif
  594. }
  595. var backgroundTask: UIBackgroundTaskIdentifier!
  596. backgroundTask = sharedApplication.beginBackgroundTask {
  597. endBackgroundTask(&backgroundTask!)
  598. }
  599. cleanExpiredDiskCache {
  600. endBackgroundTask(&backgroundTask!)
  601. }
  602. }
  603. #endif
  604. // MARK: Image Cache State
  605. /// Returns the cache type for a given `key` and `identifier` combination.
  606. /// This method is used for checking whether an image is cached in current cache.
  607. /// It also provides information on which kind of cache can it be found in the return value.
  608. ///
  609. /// - Parameters:
  610. /// - key: The key used for caching the image.
  611. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of
  612. /// `DefaultImageProcessor.default`.
  613. /// - Returns: A `CacheType` instance which indicates the cache status.
  614. /// `.none` means the image is not in cache or it is already expired.
  615. open func imageCachedType(
  616. forKey key: String,
  617. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> CacheType
  618. {
  619. let computedKey = key.computedKey(with: identifier)
  620. if memoryStorage.isCached(forKey: computedKey) { return .memory }
  621. if diskStorage.isCached(forKey: computedKey) { return .disk }
  622. return .none
  623. }
  624. /// Returns whether the file exists in cache for a given `key` and `identifier` combination.
  625. ///
  626. /// - Parameters:
  627. /// - key: The key used for caching the image.
  628. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of
  629. /// `DefaultImageProcessor.default`.
  630. /// - Returns: A `Bool` which indicates whether a cache could match the given `key` and `identifier` combination.
  631. ///
  632. /// - Note:
  633. /// The return value does not contain information about from which kind of storage the cache matches.
  634. /// To get the information about cache type according `CacheType`,
  635. /// use `imageCachedType(forKey:processorIdentifier:)` instead.
  636. public func isCached(
  637. forKey key: String,
  638. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> Bool
  639. {
  640. return imageCachedType(forKey: key, processorIdentifier: identifier).cached
  641. }
  642. /// Gets the hash used as cache file name for the key.
  643. ///
  644. /// - Parameters:
  645. /// - key: The key used for caching the image.
  646. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of
  647. /// `DefaultImageProcessor.default`.
  648. /// - Returns: The hash which is used as the cache file name.
  649. ///
  650. /// - Note:
  651. /// By default, for a given combination of `key` and `identifier`, `ImageCache` will use the value
  652. /// returned by this method as the cache file name. You can use this value to check and match cache file
  653. /// if you need.
  654. open func hash(
  655. forKey key: String,
  656. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
  657. {
  658. let computedKey = key.computedKey(with: identifier)
  659. return diskStorage.cacheFileName(forKey: computedKey)
  660. }
  661. /// Calculates the size taken by the disk storage.
  662. /// It is the total file size of all cached files in the `diskStorage` on disk in bytes.
  663. ///
  664. /// - Parameter handler: Called with the size calculating finishes. This closure is invoked from the main queue.
  665. open func calculateDiskStorageSize(completion handler: @escaping ((Result<UInt, KingfisherError>) -> Void)) {
  666. ioQueue.async {
  667. do {
  668. let size = try self.diskStorage.totalSize()
  669. DispatchQueue.main.async { handler(.success(size)) }
  670. } catch {
  671. if let error = error as? KingfisherError {
  672. DispatchQueue.main.async { handler(.failure(error)) }
  673. } else {
  674. assertionFailure("The internal thrown error should be a `KingfisherError`.")
  675. }
  676. }
  677. }
  678. }
  679. /// Gets the cache path for the key.
  680. /// It is useful for projects with web view or anyone that needs access to the local file path.
  681. ///
  682. /// i.e. Replacing the `<img src='path_for_key'>` tag in your HTML.
  683. ///
  684. /// - Parameters:
  685. /// - key: The key used for caching the image.
  686. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of
  687. /// `DefaultImageProcessor.default`.
  688. /// - Returns: The disk path of cached image under the given `key` and `identifier`.
  689. ///
  690. /// - Note:
  691. /// This method does not guarantee there is an image already cached in the returned path. It just gives your
  692. /// the path that the image should be, if it exists in disk storage.
  693. ///
  694. /// You could use `isCached(forKey:)` method to check whether the image is cached under that key in disk.
  695. open func cachePath(
  696. forKey key: String,
  697. processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
  698. {
  699. let computedKey = key.computedKey(with: identifier)
  700. return diskStorage.cacheFileURL(forKey: computedKey).path
  701. }
  702. }
  703. extension Dictionary {
  704. func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] {
  705. return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 }
  706. }
  707. }
  708. #if !os(macOS) && !os(watchOS)
  709. // MARK: - For App Extensions
  710. extension UIApplication: KingfisherCompatible { }
  711. extension KingfisherWrapper where Base: UIApplication {
  712. public static var shared: UIApplication? {
  713. let selector = NSSelectorFromString("sharedApplication")
  714. guard Base.responds(to: selector) else { return nil }
  715. return Base.perform(selector).takeUnretainedValue() as? UIApplication
  716. }
  717. }
  718. #endif
  719. extension String {
  720. func computedKey(with identifier: String) -> String {
  721. if identifier.isEmpty {
  722. return self
  723. } else {
  724. return appending("@\(identifier)")
  725. }
  726. }
  727. }