ImageCache.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. //
  2. // ImageCache.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  6. //
  7. // Copyright (c) 2016 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. public 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 var 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. private let defaultCacheName = "default"
  45. private let cacheReverseDNS = "com.onevcat.Kingfisher.ImageCache."
  46. private let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue."
  47. private let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue."
  48. private let defaultCacheInstance = ImageCache(name: defaultCacheName)
  49. private let defaultMaxCachePeriodInSecond: TimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week
  50. /// It represents a task of retrieving image. You can call `cancel` on it to stop the process.
  51. public typealias RetrieveImageDiskTask = DispatchWorkItem
  52. /**
  53. Cache type of a cached image.
  54. - None: The image is not cached yet when retrieving it.
  55. - Memory: The image is cached in memory.
  56. - Disk: The image is cached in disk.
  57. */
  58. public enum CacheType {
  59. case none, memory, disk
  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 should use an `ImageCache`
  64. /// object to manipulate memory and disk cache for Kingfisher.
  65. public 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 all cached images in memory.
  69. public var maxMemoryCost: UInt = 0 {
  70. didSet {
  71. self.memoryCache.totalCostLimit = Int(maxMemoryCost)
  72. }
  73. }
  74. //Disk
  75. fileprivate let ioQueue: DispatchQueue
  76. fileprivate var fileManager: FileManager!
  77. ///The disk cache location.
  78. public let diskCachePath: String
  79. /// The longest time duration of the cache being stored in disk. Default is 1 week.
  80. public var maxCachePeriodInSecond = defaultMaxCachePeriodInSecond
  81. /// The largest disk size can be taken for the cache. It is the total allocated size of cached files in bytes.
  82. /// Default is 0, which means no limit.
  83. public var maxDiskCacheSize: UInt = 0
  84. fileprivate let processQueue: DispatchQueue
  85. /// The default cache.
  86. public class var `default`: ImageCache {
  87. return defaultCacheInstance
  88. }
  89. /**
  90. Init method. Passing a name for the cache. It represents a cache folder in the memory and disk.
  91. - parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name
  92. appending to the cache path. This value should not be an empty string.
  93. - parameter path: Optional - Location of cache path on disk. If `nil` is passed (the default value),
  94. the cache folder in of your app will be used. If you want to cache some user generating images,
  95. you could pass the Documentation path here.
  96. - returns: The cache object.
  97. */
  98. public init(name: String, path: String? = nil) {
  99. if name.isEmpty {
  100. fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
  101. }
  102. let cacheName = cacheReverseDNS + name
  103. memoryCache.name = cacheName
  104. let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
  105. diskCachePath = (dstPath as NSString).appendingPathComponent(cacheName)
  106. ioQueue = DispatchQueue(label: ioQueueName + name)
  107. processQueue = DispatchQueue(label: processQueueName + name, attributes: .concurrent)
  108. ioQueue.sync { fileManager = FileManager() }
  109. #if !os(macOS) && !os(watchOS)
  110. NotificationCenter.default.addObserver(
  111. self, selector: #selector(clearMemoryCache), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
  112. NotificationCenter.default.addObserver(
  113. self, selector: #selector(cleanExpiredDiskCache_), name: .UIApplicationWillTerminate, object: nil)
  114. NotificationCenter.default.addObserver(
  115. self, selector: #selector(backgroundCleanExpiredDiskCache), name: .UIApplicationDidEnterBackground, object: nil)
  116. #endif
  117. }
  118. deinit {
  119. NotificationCenter.default.removeObserver(self)
  120. }
  121. }
  122. // MARK: - Store & Remove
  123. extension ImageCache {
  124. /**
  125. Store an image to cache. It will be saved to both memory and disk. It is an async operation.
  126. - parameter image: The image to be stored.
  127. - parameter originalData: The original data of the image.
  128. Kingfisher will use it to check the format of the image and optimize cache size on disk.
  129. If `nil` is supplied, the image data will be saved as a normalized PNG file.
  130. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage.
  131. - parameter key: Key for the image.
  132. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it.
  133. This identifier will be used to generate a corresponding key for the combination of `key` and processor.
  134. - parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory.
  135. - parameter completionHandler: Called when store operation completes.
  136. */
  137. public func storeImage(_ image: Image,
  138. originalData: Data? = nil,
  139. forKey key: String,
  140. processorIdentifier identifier: String = "",
  141. toDisk: Bool = true,
  142. completionHandler: (() -> Void)? = nil)
  143. {
  144. let computedKey = key.computedKey(with: identifier)
  145. memoryCache.setObject(image, forKey: computedKey as NSString, cost: image.kf_imageCost)
  146. func callHandlerInMainQueue() {
  147. if let handler = completionHandler {
  148. DispatchQueue.main.async {
  149. handler()
  150. }
  151. }
  152. }
  153. if toDisk {
  154. ioQueue.async(execute: {
  155. let imageFormat = originalData?.kf_imageFormat ?? .unknown
  156. let data: Data?
  157. switch imageFormat {
  158. case .PNG: data = image.pngRepresentation()
  159. case .JPEG: data = image.jpegRepresentation(compressionQuality: 1.0)
  160. case .GIF: data = image.gifRepresentation()
  161. case .unknown: data = originalData ?? image.kf_normalized().pngRepresentation()
  162. }
  163. if let data = data {
  164. if !self.fileManager.fileExists(atPath: self.diskCachePath) {
  165. do {
  166. try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
  167. } catch _ {}
  168. }
  169. self.fileManager.createFile(atPath: self.cachePathForKey(computedKey), contents: data, attributes: nil)
  170. }
  171. callHandlerInMainQueue()
  172. })
  173. } else {
  174. callHandlerInMainQueue()
  175. }
  176. }
  177. /**
  178. Remove the image for key for the cache. It will be opted out from both memory and disk.
  179. It is an async operation.
  180. - parameter key: Key for the image.
  181. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it.
  182. This identifier will be used to generate a corresponding key for the combination of `key` and processor.
  183. - parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory.
  184. - parameter completionHandler: Called when removal operation completes.
  185. */
  186. public func removeImage(forKey key: String,
  187. processorIdentifier identifier: String = "",
  188. fromDisk: Bool = true,
  189. completionHandler: (() -> Void)? = nil)
  190. {
  191. let computedKey = key.computedKey(with: identifier)
  192. memoryCache.removeObject(forKey: computedKey as NSString)
  193. func callHandlerInMainQueue() {
  194. if let handler = completionHandler {
  195. DispatchQueue.main.async {
  196. handler()
  197. }
  198. }
  199. }
  200. if fromDisk {
  201. ioQueue.async{
  202. do {
  203. try self.fileManager.removeItem(atPath: self.cachePathForKey(computedKey))
  204. } catch _ {}
  205. callHandlerInMainQueue()
  206. }
  207. } else {
  208. callHandlerInMainQueue()
  209. }
  210. }
  211. }
  212. // MARK: - Get data from cache
  213. extension ImageCache {
  214. /**
  215. Get an image for a key from memory or disk.
  216. - parameter key: Key for the image.
  217. - parameter options: Options of retrieving image. If you need to retrieve an image which was
  218. stored with a specified `ImageProcessor`, pass the processor in the option too.
  219. - parameter completionHandler: Called when getting operation completes with image result and cached type of
  220. this image. If there is no such key cached, the image will be `nil`.
  221. - returns: The retrieving task.
  222. */
  223. @discardableResult public func retrieveImage(forKey key: String,
  224. options: KingfisherOptionsInfo?,
  225. completionHandler: ((Image?, CacheType) -> ())?) -> RetrieveImageDiskTask?
  226. {
  227. // No completion handler. Not start working and early return.
  228. guard let completionHandler = completionHandler else {
  229. return nil
  230. }
  231. var block: RetrieveImageDiskTask?
  232. let options = options ?? KingfisherEmptyOptionsInfo
  233. let computedKey = key.computedKey(with: options.processor.identifier)
  234. if let image = self.retrieveImageInMemoryCache(forKey: computedKey) {
  235. options.callbackDispatchQueue.safeAsync {
  236. completionHandler(image, .memory)
  237. }
  238. } else {
  239. var sSelf: ImageCache! = self
  240. block = DispatchWorkItem(block: {
  241. // Begin to load image from disk
  242. if let image = sSelf.retrieveImageInDiskCacheForKey(computedKey, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData) {
  243. if options.backgroundDecode {
  244. sSelf.processQueue.async(execute: { () -> Void in
  245. let result = image.kf_decoded(scale: options.scaleFactor)
  246. sSelf.storeImage(result!, forKey: computedKey, toDisk: false, completionHandler: nil)
  247. options.callbackDispatchQueue.safeAsync {
  248. completionHandler(result, .memory)
  249. sSelf = nil
  250. }
  251. })
  252. } else {
  253. sSelf.storeImage(image, forKey: computedKey, toDisk: false, completionHandler: nil)
  254. options.callbackDispatchQueue.safeAsync {
  255. completionHandler(image, .disk)
  256. sSelf = nil
  257. }
  258. }
  259. } else {
  260. // No image found from either memory or disk
  261. options.callbackDispatchQueue.safeAsync {
  262. completionHandler(nil, .none)
  263. sSelf = nil
  264. }
  265. }
  266. })
  267. sSelf.ioQueue.async(execute: block!)
  268. }
  269. return block
  270. }
  271. /**
  272. Get an image for a key from memory.
  273. - parameter key: Key for the image.
  274. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it.
  275. This identifier will be used to generate a corresponding key for the combination of `key` and processor.
  276. - returns: The image object if it is cached, or `nil` if there is no such key in the cache.
  277. */
  278. public func retrieveImageInMemoryCache(forKey key: String, processIdentifier identifier: String = "") -> Image? {
  279. let computedKey = key.computedKey(with: identifier)
  280. return memoryCache.object(forKey: computedKey as NSString) as? Image
  281. }
  282. /**
  283. Get an image for a key from disk.
  284. - parameter key: Key for the image.
  285. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it.
  286. This identifier will be used to generate a corresponding key for the combination of `key` and processor.
  287. - parameter scale: The scale factor to assume when interpreting the image data.
  288. - parameter preloadAllGIFData: Whether all GIF data should be loaded. If true, you can set the loaded image to a regular UIImageView to play
  289. the GIF animation. Otherwise, you should use `AnimatedImageView` to play it. Default is `false`
  290. - returns: The image object if it is cached, or `nil` if there is no such key in the cache.
  291. */
  292. public func retrieveImageInDiskCacheForKey(_ key: String, processIdentifier identifier: String = "", scale: CGFloat = 1.0, preloadAllGIFData: Bool = false) -> Image? {
  293. let computedKey = key.computedKey(with: identifier)
  294. return diskImageForKey(computedKey, scale: scale, preloadAllGIFData: preloadAllGIFData)
  295. }
  296. }
  297. // MARK: - Clear & Clean
  298. extension ImageCache {
  299. /**
  300. Clear memory cache.
  301. */
  302. @objc public func clearMemoryCache() {
  303. memoryCache.removeAllObjects()
  304. }
  305. /**
  306. Clear disk cache.
  307. */
  308. private func clearDiskCache_() {
  309. clearDiskCache(with: nil)
  310. }
  311. /**
  312. Clear disk cache. This is an async operation.
  313. - parameter completionHander: Called after the operation completes.
  314. */
  315. public func clearDiskCache(with completionHander: (()->())? = nil) {
  316. ioQueue.async(execute: { () -> Void in
  317. do {
  318. try self.fileManager.removeItem(atPath: self.diskCachePath)
  319. try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
  320. } catch _ {
  321. }
  322. if let completionHander = completionHander {
  323. DispatchQueue.main.async(execute: { () -> Void in
  324. completionHander()
  325. })
  326. }
  327. })
  328. }
  329. /**
  330. Clean expired disk cache. This is an async operation.
  331. */
  332. @objc fileprivate func cleanExpiredDiskCache_() {
  333. cleanExpiredDiskCache(with: nil)
  334. }
  335. /**
  336. Clean expired disk cache. This is an async operation.
  337. - parameter completionHandler: Called after the operation completes.
  338. */
  339. public func cleanExpiredDiskCache(with completionHandler: (()->())? = nil) {
  340. // Do things in cocurrent io queue
  341. ioQueue.async(execute: { () -> Void in
  342. var (URLsToDelete, diskCacheSize, cachedFiles) = self.travelCachedFiles(onlyForCacheSize: false)
  343. for fileURL in URLsToDelete {
  344. do {
  345. try self.fileManager.removeItem(at: fileURL)
  346. } catch _ {
  347. }
  348. }
  349. if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize {
  350. let targetSize = self.maxDiskCacheSize / 2
  351. // Sort files by last modify date. We want to clean from the oldest files.
  352. let sortedFiles = cachedFiles.keysSortedByValue {
  353. resourceValue1, resourceValue2 -> Bool in
  354. if let date1 = resourceValue1.contentAccessDate,
  355. let date2 = resourceValue2.contentAccessDate
  356. {
  357. return date1.compare(date2) == .orderedAscending
  358. }
  359. // Not valid date information. This should not happen. Just in case.
  360. return true
  361. }
  362. for fileURL in sortedFiles {
  363. do {
  364. try self.fileManager.removeItem(at: fileURL)
  365. } catch {
  366. }
  367. URLsToDelete.append(fileURL)
  368. if let fileSize = cachedFiles[fileURL]?.totalFileAllocatedSize {
  369. diskCacheSize -= UInt(fileSize)
  370. }
  371. if diskCacheSize < targetSize {
  372. break
  373. }
  374. }
  375. }
  376. DispatchQueue.main.async(execute: { () -> Void in
  377. if URLsToDelete.count != 0 {
  378. let cleanedHashes = URLsToDelete.map({ (url) -> String in
  379. return url.lastPathComponent
  380. })
  381. NotificationCenter.default.post(name: .KingfisherDidCleanDiskCache, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
  382. }
  383. completionHandler?()
  384. })
  385. })
  386. }
  387. fileprivate func travelCachedFiles(onlyForCacheSize: Bool) -> (URLsToDelete: [URL], diskCacheSize: UInt, cachedFiles: [URL: URLResourceValues]) {
  388. let diskCacheURL = URL(fileURLWithPath: diskCachePath)
  389. let resourceKeys: Set<URLResourceKey> = [.isDirectoryKey, .contentAccessDateKey, .totalFileAllocatedSizeKey]
  390. let expiredDate = Date(timeIntervalSinceNow: -maxCachePeriodInSecond)
  391. var cachedFiles = [URL: URLResourceValues]()
  392. var URLsToDelete = [URL]()
  393. var diskCacheSize: UInt = 0
  394. if let fileEnumerator = self.fileManager.enumerator(at: diskCacheURL, includingPropertiesForKeys: Array(resourceKeys), options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles, errorHandler: nil),
  395. let urls = fileEnumerator.allObjects as? [URL] {
  396. for fileURL in urls {
  397. do {
  398. let resourceValues = try fileURL.resourceValues(forKeys: resourceKeys)
  399. // If it is a Directory. Continue to next file URL.
  400. if resourceValues.isDirectory == true {
  401. continue
  402. }
  403. if !onlyForCacheSize {
  404. // If this file is expired, add it to URLsToDelete
  405. if let lastAccessData = resourceValues.contentAccessDate {
  406. if (lastAccessData as NSDate).laterDate(expiredDate) == expiredDate {
  407. URLsToDelete.append(fileURL)
  408. continue
  409. }
  410. }
  411. }
  412. if let fileSize = resourceValues.totalFileAllocatedSize {
  413. diskCacheSize += UInt(fileSize)
  414. if !onlyForCacheSize {
  415. cachedFiles[fileURL] = resourceValues
  416. }
  417. }
  418. } catch _ {
  419. }
  420. }
  421. }
  422. return (URLsToDelete, diskCacheSize, cachedFiles)
  423. }
  424. #if !os(macOS) && !os(watchOS)
  425. /**
  426. Clean expired disk cache when app in background. This is an async operation.
  427. In most cases, you should not call this method explicitly.
  428. It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
  429. */
  430. @objc public func backgroundCleanExpiredDiskCache() {
  431. // if 'sharedApplication()' is unavailable, then return
  432. guard let sharedApplication = UIApplication.kf_shared else { return }
  433. func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) {
  434. sharedApplication.endBackgroundTask(task)
  435. task = UIBackgroundTaskInvalid
  436. }
  437. var backgroundTask: UIBackgroundTaskIdentifier!
  438. backgroundTask = sharedApplication.beginBackgroundTask {
  439. endBackgroundTask(&backgroundTask!)
  440. }
  441. cleanExpiredDiskCache {
  442. endBackgroundTask(&backgroundTask!)
  443. }
  444. }
  445. #endif
  446. }
  447. // MARK: - Check cache status
  448. extension ImageCache {
  449. /**
  450. * Cache result for checking whether an image is cached for a key.
  451. */
  452. public struct CacheCheckResult {
  453. public let cached: Bool
  454. public let cacheType: CacheType?
  455. }
  456. /**
  457. Determine if a cached image exists for the given image, as keyed by the URL. It will return true if the
  458. image is found either in memory or on disk. Essentially as long as there is a cache of the image somewhere
  459. true is returned. A convenience method that decodes `isImageCachedForKey`.
  460. - parameter resource: The target resource.
  461. `cacheKey` property of this resource will be used to check whether this image be cached or not.
  462. - returns: True if the image is cached, false otherwise.
  463. */
  464. public func cachedImageExists(for resource: Resource) -> Bool {
  465. let result = isImageCachedForKey(resource.cacheKey)
  466. return result.cached
  467. }
  468. /**
  469. Check whether an image is cached for a key.
  470. - parameter key: Key for the image.
  471. - returns: The check result.
  472. */
  473. public func isImageCachedForKey(_ key: String) -> CacheCheckResult {
  474. if memoryCache.object(forKey: key as NSString) != nil {
  475. return CacheCheckResult(cached: true, cacheType: .memory)
  476. }
  477. let filePath = cachePathForKey(key)
  478. var diskCached = false
  479. ioQueue.sync { () -> Void in
  480. diskCached = self.fileManager.fileExists(atPath: filePath)
  481. }
  482. if diskCached {
  483. return CacheCheckResult(cached: true, cacheType: .disk)
  484. }
  485. return CacheCheckResult(cached: false, cacheType: nil)
  486. }
  487. /**
  488. Get the hash for the key. This could be used for matching files.
  489. - parameter key: The key which is used for caching.
  490. - returns: Corresponding hash.
  491. */
  492. public func hashForKey(_ key: String) -> String {
  493. return cacheFileNameForKey(key)
  494. }
  495. /**
  496. Calculate the disk size taken by cache.
  497. It is the total allocated size of the cached files in bytes.
  498. - parameter completionHandler: Called with the calculated size when finishes.
  499. */
  500. public func calculateDiskCacheSize(completionHandler: ((_ size: UInt) -> ())) {
  501. ioQueue.async(execute: { () -> Void in
  502. let (_, diskCacheSize, _) = self.travelCachedFiles(onlyForCacheSize: true)
  503. DispatchQueue.main.async(execute: { () -> Void in
  504. completionHandler(diskCacheSize)
  505. })
  506. })
  507. }
  508. /**
  509. Get the cache path for the key.
  510. It is useful for projects with UIWebView or anyone that needs access to the local file path.
  511. i.e. `<img src='path_for_key'>`
  512. - Note: This method does not guarantee there is an image already cached in the path.
  513. You could use `isImageCachedForKey` method to check whether the image is cached under that key.
  514. */
  515. public func cachePathForKey(_ key: String) -> String {
  516. let fileName = cacheFileNameForKey(key)
  517. return (diskCachePath as NSString).appendingPathComponent(fileName)
  518. }
  519. }
  520. // MARK: - Internal Helper
  521. extension ImageCache {
  522. func diskImageForKey(_ key: String, scale: CGFloat, preloadAllGIFData: Bool) -> Image? {
  523. if let data = diskImageDataForKey(key) {
  524. return Image.kf_image(data: data, scale: scale, preloadAllGIFData: preloadAllGIFData)
  525. } else {
  526. return nil
  527. }
  528. }
  529. func diskImageDataForKey(_ key: String) -> Data? {
  530. let filePath = cachePathForKey(key)
  531. return (try? Data(contentsOf: URL(fileURLWithPath: filePath)))
  532. }
  533. func cacheFileNameForKey(_ key: String) -> String {
  534. return key.kf_MD5
  535. }
  536. }
  537. extension Image {
  538. var kf_imageCost: Int {
  539. return kf_images == nil ?
  540. Int(size.height * size.width * kf_scale * kf_scale) :
  541. Int(size.height * size.width * kf_scale * kf_scale) * kf_images!.count
  542. }
  543. }
  544. extension Dictionary {
  545. func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] {
  546. return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 }
  547. }
  548. }
  549. #if !os(macOS) && !os(watchOS)
  550. // MARK: - For App Extensions
  551. extension UIApplication {
  552. public static var kf_shared: UIApplication? {
  553. let selector = NSSelectorFromString("sharedApplication")
  554. guard responds(to: selector) else { return nil }
  555. return perform(selector).takeUnretainedValue() as? UIApplication
  556. }
  557. }
  558. #endif
  559. extension String {
  560. func computedKey(with identifier: String) -> String {
  561. if identifier.isEmpty {
  562. return self
  563. } else {
  564. return appending("@\(identifier)")
  565. }
  566. }
  567. }