ImageCache.swift 34 KB

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