ImageCache.swift 27 KB

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