2
0

ImageCache.swift 26 KB

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