ImageCache.swift 37 KB

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