ImageCache.swift 25 KB

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