ImageCache.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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. /**
  33. This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger this notification.
  34. The `object` of this notification is the `ImageCache` object which sends the notification.
  35. A list of removed hashes (files) could be retrieved by accessing the array under `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed.
  36. The main purpose of this notification is supplying a chance to maintain some necessary information on the cached files. See [this wiki](https://github.com/onevcat/Kingfisher/wiki/How-to-implement-ETag-based-304-(Not-Modified)-handling-in-Kingfisher) for a use case on it.
  37. */
  38. public static let KingfisherDidCleanDiskCache = Notification.Name.init("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache")
  39. }
  40. /**
  41. Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`.
  42. */
  43. public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash"
  44. /// It represents a task of retrieving image. You can call `cancel` on it to stop the process.
  45. public typealias RetrieveImageDiskTask = DispatchWorkItem
  46. /**
  47. Cache type of a cached image.
  48. - None: The image is not cached yet when retrieving it.
  49. - Memory: The image is cached in memory.
  50. - Disk: The image is cached in disk.
  51. */
  52. public enum CacheType {
  53. case none, memory, disk
  54. public var cached: Bool {
  55. switch self {
  56. case .memory, .disk: return true
  57. case .none: return false
  58. }
  59. }
  60. }
  61. /// `ImageCache` represents both the memory and disk cache system of Kingfisher.
  62. /// While a default image cache object will be used if you prefer the extension methods of Kingfisher,
  63. /// you can create your own cache object and configure it as your need. You could use an `ImageCache`
  64. /// object to manipulate memory and disk cache for Kingfisher.
  65. open class ImageCache {
  66. //Memory
  67. fileprivate let memoryCache = NSCache<NSString, AnyObject>()
  68. /// The largest cache cost of memory cache. The total cost is pixel count of
  69. /// all cached images in memory.
  70. /// Default is unlimited. Memory cache will be purged automatically when a
  71. /// memory warning notification is received.
  72. open var maxMemoryCost: UInt = 0 {
  73. didSet {
  74. self.memoryCache.totalCostLimit = Int(maxMemoryCost)
  75. }
  76. }
  77. //Disk
  78. fileprivate let ioQueue: DispatchQueue
  79. fileprivate var fileManager: FileManager!
  80. ///The disk cache location.
  81. public let diskCachePath: String
  82. /// The default file extension appended to cached files.
  83. open var pathExtension: String?
  84. /// The longest time duration in second of the cache being stored in disk.
  85. /// Default is 1 week (60 * 60 * 24 * 7 seconds).
  86. /// Setting this to a negative value will make the disk cache never expiring.
  87. open var maxCachePeriodInSecond: TimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week
  88. /// The largest disk size can be taken for the cache. It is the total
  89. /// allocated size of cached files in bytes.
  90. /// Default is no limit.
  91. open var maxDiskCacheSize: UInt = 0
  92. fileprivate let processQueue: DispatchQueue
  93. /// The default cache.
  94. public static let `default` = ImageCache(name: "default")
  95. /// Closure that defines the disk cache path from a given path and cacheName.
  96. public typealias DiskCachePathClosure = (String?, String) -> String
  97. /// The default DiskCachePathClosure
  98. public final class func defaultDiskCachePathClosure(path: String?, cacheName: String) -> String {
  99. let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
  100. return (dstPath as NSString).appendingPathComponent(cacheName)
  101. }
  102. /**
  103. Init method. Passing a name for the cache. It represents a cache folder in the memory and disk.
  104. - parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name
  105. appending to the cache path. This value should not be an empty string.
  106. - parameter path: Optional - Location of cache path on disk. If `nil` is passed in (the default value),
  107. the `.cachesDirectory` in of your app will be used.
  108. - parameter diskCachePathClosure: Closure that takes in an optional initial path string and generates
  109. the final disk cache path. You could use it to fully customize your cache path.
  110. */
  111. public init(name: String,
  112. path: String? = nil,
  113. diskCachePathClosure: DiskCachePathClosure = ImageCache.defaultDiskCachePathClosure)
  114. {
  115. if name.isEmpty {
  116. fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
  117. }
  118. let cacheName = "com.onevcat.Kingfisher.ImageCache.\(name)"
  119. memoryCache.name = cacheName
  120. diskCachePath = diskCachePathClosure(path, cacheName)
  121. let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(name)"
  122. ioQueue = DispatchQueue(label: ioQueueName)
  123. let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue.\(name)"
  124. processQueue = DispatchQueue(label: processQueueName, attributes: .concurrent)
  125. ioQueue.sync { fileManager = FileManager() }
  126. #if !os(macOS) && !os(watchOS)
  127. #if swift(>=4.2)
  128. let memoryNotification = UIApplication.didReceiveMemoryWarningNotification
  129. let terminateNotification = UIApplication.willTerminateNotification
  130. let enterbackgroundNotification = UIApplication.didEnterBackgroundNotification
  131. #else
  132. let memoryNotification = NSNotification.Name.UIApplicationDidReceiveMemoryWarning
  133. let terminateNotification = NSNotification.Name.UIApplicationWillTerminate
  134. let enterbackgroundNotification = NSNotification.Name.UIApplicationDidEnterBackground
  135. #endif
  136. NotificationCenter.default.addObserver(
  137. self, selector: #selector(clearMemoryCache), name: memoryNotification, object: nil)
  138. NotificationCenter.default.addObserver(
  139. self, selector: #selector(cleanExpiredDiskCache), name: terminateNotification, object: nil)
  140. NotificationCenter.default.addObserver(
  141. self, selector: #selector(backgroundCleanExpiredDiskCache), name: enterbackgroundNotification, object: nil)
  142. #endif
  143. }
  144. deinit {
  145. NotificationCenter.default.removeObserver(self)
  146. }
  147. // MARK: - Store & Remove
  148. /**
  149. Store an image to cache. It will be saved to both memory and disk. It is an async operation.
  150. - parameter image: The image to be stored.
  151. - parameter original: The original data of the image.
  152. Kingfisher will use it to check the format of the image and optimize cache size on disk.
  153. If `nil` is supplied, the image data will be saved as a normalized PNG file.
  154. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage.
  155. - parameter key: Key for the image.
  156. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of
  157. processor to it.
  158. This identifier will be used to generate a corresponding key for the combination of `key` and processor.
  159. - parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory.
  160. - parameter completionHandler: Called when store operation completes.
  161. */
  162. open func store(_ image: Image,
  163. original: Data? = nil,
  164. forKey key: String,
  165. processorIdentifier identifier: String = "",
  166. cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
  167. toDisk: Bool = true,
  168. completionHandler: (() -> Void)? = nil)
  169. {
  170. let computedKey = key.computedKey(with: identifier)
  171. memoryCache.setObject(image, forKey: computedKey as NSString, cost: image.kf.imageCost)
  172. func callHandlerInMainQueue() {
  173. if let handler = completionHandler {
  174. DispatchQueue.main.async {
  175. handler()
  176. }
  177. }
  178. }
  179. if toDisk {
  180. ioQueue.async {
  181. if let data = serializer.data(with: image, original: original) {
  182. if !self.fileManager.fileExists(atPath: self.diskCachePath) {
  183. do {
  184. try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
  185. } catch _ {}
  186. }
  187. self.fileManager.createFile(atPath: self.cachePath(forComputedKey: computedKey), contents: data, attributes: nil)
  188. }
  189. callHandlerInMainQueue()
  190. }
  191. } else {
  192. callHandlerInMainQueue()
  193. }
  194. }
  195. /**
  196. Remove the image for key for the cache. It will be opted out from both memory and disk.
  197. It is an async operation.
  198. - parameter key: Key for the image.
  199. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it.
  200. This identifier will be used to generate a corresponding key for the combination of `key` and processor.
  201. - parameter fromMemory: Whether this image should be removed from memory or not. If false, the image won't be removed from memory.
  202. - parameter fromDisk: Whether this image should be removed from disk or not. If false, the image won't be removed from disk.
  203. - parameter completionHandler: Called when removal operation completes.
  204. */
  205. open func removeImage(forKey key: String,
  206. processorIdentifier identifier: String = "",
  207. fromMemory: Bool = true,
  208. fromDisk: Bool = true,
  209. completionHandler: (() -> Void)? = nil)
  210. {
  211. let computedKey = key.computedKey(with: identifier)
  212. if fromMemory {
  213. memoryCache.removeObject(forKey: computedKey as NSString)
  214. }
  215. func callHandlerInMainQueue() {
  216. if let handler = completionHandler {
  217. DispatchQueue.main.async {
  218. handler()
  219. }
  220. }
  221. }
  222. if fromDisk {
  223. ioQueue.async{
  224. do {
  225. try self.fileManager.removeItem(atPath: self.cachePath(forComputedKey: computedKey))
  226. } catch _ {}
  227. callHandlerInMainQueue()
  228. }
  229. } else {
  230. callHandlerInMainQueue()
  231. }
  232. }
  233. // MARK: - Get data from cache
  234. /**
  235. Get an image for a key from memory or disk.
  236. - parameter key: Key for the image.
  237. - parameter options: Options of retrieving image. If you need to retrieve an image which was
  238. stored with a specified `ImageProcessor`, pass the processor in the option too.
  239. - parameter completionHandler: Called when getting operation completes with image result and cached type of
  240. this image. If there is no such key cached, the image will be `nil`.
  241. - returns: The retrieving task.
  242. */
  243. @discardableResult
  244. open func retrieveImage(forKey key: String,
  245. options: KingfisherOptionsInfo?,
  246. completionHandler: ((Image?, CacheType) -> Void)?) -> RetrieveImageDiskTask?
  247. {
  248. // No completion handler. Not start working and early return.
  249. guard let completionHandler = completionHandler else {
  250. return nil
  251. }
  252. var block: RetrieveImageDiskTask?
  253. let options = options ?? KingfisherEmptyOptionsInfo
  254. let imageModifier = options.imageModifier
  255. if let image = self.retrieveImageInMemoryCache(forKey: key, options: options) {
  256. options.callbackDispatchQueue.safeAsync {
  257. completionHandler(imageModifier.modify(image), .memory)
  258. }
  259. } else if options.fromMemoryCacheOrRefresh { // Only allows to get images from memory cache.
  260. options.callbackDispatchQueue.safeAsync {
  261. completionHandler(nil, .none)
  262. }
  263. } else {
  264. var sSelf: ImageCache! = self
  265. block = DispatchWorkItem(block: {
  266. // Begin to load image from disk
  267. if let image = sSelf.retrieveImageInDiskCache(forKey: key, options: options) {
  268. if options.backgroundDecode {
  269. sSelf.processQueue.async {
  270. let result = image.kf.decoded
  271. sSelf.store(result,
  272. forKey: key,
  273. processorIdentifier: options.processor.identifier,
  274. cacheSerializer: options.cacheSerializer,
  275. toDisk: false,
  276. completionHandler: nil)
  277. options.callbackDispatchQueue.safeAsync {
  278. completionHandler(imageModifier.modify(result), .disk)
  279. sSelf = nil
  280. }
  281. }
  282. } else {
  283. sSelf.store(image,
  284. forKey: key,
  285. processorIdentifier: options.processor.identifier,
  286. cacheSerializer: options.cacheSerializer,
  287. toDisk: false,
  288. completionHandler: nil
  289. )
  290. options.callbackDispatchQueue.safeAsync {
  291. completionHandler(imageModifier.modify(image), .disk)
  292. sSelf = nil
  293. }
  294. }
  295. } else {
  296. // No image found from either memory or disk
  297. options.callbackDispatchQueue.safeAsync {
  298. completionHandler(nil, .none)
  299. sSelf = nil
  300. }
  301. }
  302. })
  303. sSelf.ioQueue.async(execute: block!)
  304. }
  305. return block
  306. }
  307. /**
  308. Get an image for a key from memory.
  309. - parameter key: Key for the image.
  310. - parameter options: Options of retrieving image. If you need to retrieve an image which was
  311. stored with a specified `ImageProcessor`, pass the processor in the option too.
  312. - returns: The image object if it is cached, or `nil` if there is no such key in the cache.
  313. */
  314. open func retrieveImageInMemoryCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? {
  315. let options = options ?? KingfisherEmptyOptionsInfo
  316. let computedKey = key.computedKey(with: options.processor.identifier)
  317. return memoryCache.object(forKey: computedKey as NSString) as? Image
  318. }
  319. /**
  320. Get an image for a key from disk.
  321. - parameter key: Key for the image.
  322. - parameter options: Options of retrieving image. If you need to retrieve an image which was
  323. stored with a specified `ImageProcessor`, pass the processor in the option too.
  324. - returns: The image object if it is cached, or `nil` if there is no such key in the cache.
  325. */
  326. open func retrieveImageInDiskCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? {
  327. let options = options ?? KingfisherEmptyOptionsInfo
  328. let computedKey = key.computedKey(with: options.processor.identifier)
  329. return diskImage(forComputedKey: computedKey, serializer: options.cacheSerializer, options: options)
  330. }
  331. // MARK: - Clear & Clean
  332. /**
  333. Clear memory cache.
  334. */
  335. @objc public func clearMemoryCache() {
  336. memoryCache.removeAllObjects()
  337. }
  338. /**
  339. Clear disk cache. This is an async operation.
  340. - parameter completionHander: Called after the operation completes.
  341. */
  342. open func clearDiskCache(completion handler: (()->())? = nil) {
  343. ioQueue.async {
  344. do {
  345. try self.fileManager.removeItem(atPath: self.diskCachePath)
  346. try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
  347. } catch _ { }
  348. if let handler = handler {
  349. DispatchQueue.main.async {
  350. handler()
  351. }
  352. }
  353. }
  354. }
  355. /**
  356. Clean expired disk cache. This is an async operation.
  357. */
  358. @objc fileprivate func cleanExpiredDiskCache() {
  359. cleanExpiredDiskCache(completion: nil)
  360. }
  361. /**
  362. Clean expired disk cache. This is an async operation.
  363. - parameter completionHandler: Called after the operation completes.
  364. */
  365. open func cleanExpiredDiskCache(completion handler: (()->())? = nil) {
  366. // Do things in concurrent io queue
  367. ioQueue.async {
  368. var (URLsToDelete, diskCacheSize, cachedFiles) = self.travelCachedFiles(onlyForCacheSize: false)
  369. for fileURL in URLsToDelete {
  370. do {
  371. try self.fileManager.removeItem(at: fileURL)
  372. } catch _ { }
  373. }
  374. if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize {
  375. let targetSize = self.maxDiskCacheSize / 2
  376. // Sort files by last modify date. We want to clean from the oldest files.
  377. let sortedFiles = cachedFiles.keysSortedByValue {
  378. resourceValue1, resourceValue2 -> Bool in
  379. if let date1 = resourceValue1.contentAccessDate,
  380. let date2 = resourceValue2.contentAccessDate
  381. {
  382. return date1.compare(date2) == .orderedAscending
  383. }
  384. // Not valid date information. This should not happen. Just in case.
  385. return true
  386. }
  387. for fileURL in sortedFiles {
  388. do {
  389. try self.fileManager.removeItem(at: fileURL)
  390. } catch { }
  391. URLsToDelete.append(fileURL)
  392. if let fileSize = cachedFiles[fileURL]?.totalFileAllocatedSize {
  393. diskCacheSize -= UInt(fileSize)
  394. }
  395. if diskCacheSize < targetSize {
  396. break
  397. }
  398. }
  399. }
  400. DispatchQueue.main.async {
  401. if URLsToDelete.count != 0 {
  402. let cleanedHashes = URLsToDelete.map { $0.lastPathComponent }
  403. NotificationCenter.default.post(name: .KingfisherDidCleanDiskCache, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
  404. }
  405. handler?()
  406. }
  407. }
  408. }
  409. fileprivate func travelCachedFiles(onlyForCacheSize: Bool) -> (urlsToDelete: [URL], diskCacheSize: UInt, cachedFiles: [URL: URLResourceValues]) {
  410. let diskCacheURL = URL(fileURLWithPath: diskCachePath)
  411. let resourceKeys: Set<URLResourceKey> = [.isDirectoryKey, .contentAccessDateKey, .totalFileAllocatedSizeKey]
  412. let expiredDate: Date? = (maxCachePeriodInSecond < 0) ? nil : Date(timeIntervalSinceNow: -maxCachePeriodInSecond)
  413. var cachedFiles = [URL: URLResourceValues]()
  414. var urlsToDelete = [URL]()
  415. var diskCacheSize: UInt = 0
  416. for fileUrl in (try? fileManager.contentsOfDirectory(at: diskCacheURL, includingPropertiesForKeys: Array(resourceKeys), options: .skipsHiddenFiles)) ?? [] {
  417. do {
  418. let resourceValues = try fileUrl.resourceValues(forKeys: resourceKeys)
  419. // If it is a Directory. Continue to next file URL.
  420. if resourceValues.isDirectory == true {
  421. continue
  422. }
  423. // If this file is expired, add it to URLsToDelete
  424. if !onlyForCacheSize,
  425. let expiredDate = expiredDate,
  426. let lastAccessData = resourceValues.contentAccessDate,
  427. (lastAccessData as NSDate).laterDate(expiredDate) == expiredDate
  428. {
  429. urlsToDelete.append(fileUrl)
  430. continue
  431. }
  432. if let fileSize = resourceValues.totalFileAllocatedSize {
  433. diskCacheSize += UInt(fileSize)
  434. if !onlyForCacheSize {
  435. cachedFiles[fileUrl] = resourceValues
  436. }
  437. }
  438. } catch _ { }
  439. }
  440. return (urlsToDelete, diskCacheSize, cachedFiles)
  441. }
  442. #if !os(macOS) && !os(watchOS)
  443. /**
  444. Clean expired disk cache when app in background. This is an async operation.
  445. In most cases, you should not call this method explicitly.
  446. It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
  447. */
  448. @objc public func backgroundCleanExpiredDiskCache() {
  449. // if 'sharedApplication()' is unavailable, then return
  450. guard let sharedApplication = Kingfisher<UIApplication>.shared else { return }
  451. func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) {
  452. sharedApplication.endBackgroundTask(task)
  453. #if swift(>=4.2)
  454. task = UIBackgroundTaskIdentifier.invalid
  455. #else
  456. task = UIBackgroundTaskInvalid
  457. #endif
  458. }
  459. var backgroundTask: UIBackgroundTaskIdentifier!
  460. backgroundTask = sharedApplication.beginBackgroundTask {
  461. endBackgroundTask(&backgroundTask!)
  462. }
  463. cleanExpiredDiskCache {
  464. endBackgroundTask(&backgroundTask!)
  465. }
  466. }
  467. #endif
  468. // MARK: - Check cache status
  469. /// Cache type for checking whether an image is cached for a key in current cache.
  470. ///
  471. /// - Parameters:
  472. /// - key: Key for the image.
  473. /// - identifier: Processor identifier which used for this image. Default is empty string.
  474. /// - Returns: A `CacheType` instance which indicates the cache status. `.none` means the image is not in cache yet.
  475. open func imageCachedType(forKey key: String, processorIdentifier identifier: String = "") -> CacheType {
  476. let computedKey = key.computedKey(with: identifier)
  477. if memoryCache.object(forKey: computedKey as NSString) != nil {
  478. return .memory
  479. }
  480. let filePath = cachePath(forComputedKey: computedKey)
  481. var diskCached = false
  482. ioQueue.sync {
  483. diskCached = fileManager.fileExists(atPath: filePath)
  484. }
  485. if diskCached {
  486. return .disk
  487. }
  488. return .none
  489. }
  490. /**
  491. Get the hash for the key. This could be used for matching files.
  492. - parameter key: The key which is used for caching.
  493. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it.
  494. - returns: Corresponding hash.
  495. */
  496. open func hash(forKey key: String, processorIdentifier identifier: String = "") -> String {
  497. let computedKey = key.computedKey(with: identifier)
  498. return cacheFileName(forComputedKey: computedKey)
  499. }
  500. /**
  501. Calculate the disk size taken by cache.
  502. It is the total allocated size of the cached files in bytes.
  503. - parameter completionHandler: Called with the calculated size when finishes.
  504. */
  505. open func calculateDiskCacheSize(completion handler: @escaping ((_ size: UInt) -> Void)) {
  506. ioQueue.async {
  507. let (_, diskCacheSize, _) = self.travelCachedFiles(onlyForCacheSize: true)
  508. DispatchQueue.main.async {
  509. handler(diskCacheSize)
  510. }
  511. }
  512. }
  513. /**
  514. Get the cache path for the key.
  515. It is useful for projects with UIWebView or anyone that needs access to the local file path.
  516. i.e. Replace the `<img src='path_for_key'>` tag in your HTML.
  517. - Note: This method does not guarantee there is an image already cached in the path. It just returns the path
  518. that the image should be.
  519. You could use `isImageCached(forKey:)` method to check whether the image is cached under that key.
  520. */
  521. open func cachePath(forKey key: String, processorIdentifier identifier: String = "") -> String {
  522. let computedKey = key.computedKey(with: identifier)
  523. return cachePath(forComputedKey: computedKey)
  524. }
  525. open func cachePath(forComputedKey key: String) -> String {
  526. let fileName = cacheFileName(forComputedKey: key)
  527. return (diskCachePath as NSString).appendingPathComponent(fileName)
  528. }
  529. }
  530. // MARK: - Internal Helper
  531. extension ImageCache {
  532. func diskImage(forComputedKey key: String, serializer: CacheSerializer, options: KingfisherOptionsInfo) -> Image? {
  533. if let data = diskImageData(forComputedKey: key) {
  534. return serializer.image(with: data, options: options)
  535. } else {
  536. return nil
  537. }
  538. }
  539. func diskImageData(forComputedKey key: String) -> Data? {
  540. let filePath = cachePath(forComputedKey: key)
  541. return (try? Data(contentsOf: URL(fileURLWithPath: filePath)))
  542. }
  543. func cacheFileName(forComputedKey key: String) -> String {
  544. if let ext = self.pathExtension {
  545. return (key.kf.md5 as NSString).appendingPathExtension(ext)!
  546. }
  547. return key.kf.md5
  548. }
  549. }
  550. // MARK: - Deprecated
  551. extension ImageCache {
  552. /**
  553. * Cache result for checking whether an image is cached for a key.
  554. */
  555. @available(*, deprecated,
  556. message: "CacheCheckResult is deprecated. Use imageCachedType(forKey:processorIdentifier:) API instead.")
  557. public struct CacheCheckResult {
  558. public let cached: Bool
  559. public let cacheType: CacheType?
  560. }
  561. /**
  562. Check whether an image is cached for a key.
  563. - parameter key: Key for the image.
  564. - returns: The check result.
  565. */
  566. @available(*, deprecated,
  567. message: "Use imageCachedType(forKey:processorIdentifier:) instead. CacheCheckResult.none indicates not being cached.",
  568. renamed: "imageCachedType(forKey:processorIdentifier:)")
  569. open func isImageCached(forKey key: String, processorIdentifier identifier: String = "") -> CacheCheckResult {
  570. let result = imageCachedType(forKey: key, processorIdentifier: identifier)
  571. switch result {
  572. case .memory, .disk:
  573. return CacheCheckResult(cached: true, cacheType: result)
  574. case .none:
  575. return CacheCheckResult(cached: false, cacheType: nil)
  576. }
  577. }
  578. }
  579. extension Kingfisher where Base: Image {
  580. var imageCost: Int {
  581. return images == nil ?
  582. Int(size.height * size.width * scale * scale) :
  583. Int(size.height * size.width * scale * scale) * images!.count
  584. }
  585. }
  586. extension Dictionary {
  587. func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] {
  588. return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 }
  589. }
  590. }
  591. #if !os(macOS) && !os(watchOS)
  592. // MARK: - For App Extensions
  593. extension UIApplication: KingfisherCompatible { }
  594. extension Kingfisher where Base: UIApplication {
  595. public static var shared: UIApplication? {
  596. let selector = NSSelectorFromString("sharedApplication")
  597. guard Base.responds(to: selector) else { return nil }
  598. return Base.perform(selector).takeUnretainedValue() as? UIApplication
  599. }
  600. }
  601. #endif
  602. extension String {
  603. func computedKey(with identifier: String) -> String {
  604. if identifier.isEmpty {
  605. return self
  606. } else {
  607. return appending("@\(identifier)")
  608. }
  609. }
  610. }