ImageCache.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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(OSX)
  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 = "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: NSTimeInterval = 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 = dispatch_block_t
  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()
  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: dispatch_queue_t
  71. private var fileManager: NSFileManager!
  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: dispatch_queue_t
  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, NSSearchPathDomainMask.UserDomainMask, true).first!
  97. diskCachePath = (dstPath as NSString).stringByAppendingPathComponent(cacheName)
  98. ioQueue = dispatch_queue_create(ioQueueName + name, DISPATCH_QUEUE_SERIAL)
  99. processQueue = dispatch_queue_create(processQueueName + name, DISPATCH_QUEUE_CONCURRENT)
  100. dispatch_sync(ioQueue, { () -> Void in
  101. self.fileManager = NSFileManager()
  102. })
  103. #if !os(OSX) && !os(watchOS)
  104. NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache", name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
  105. NSNotificationCenter.defaultCenter().addObserver(self, selector: "cleanExpiredDiskCache", name: UIApplicationWillTerminateNotification, object: nil)
  106. NSNotificationCenter.defaultCenter().addObserver(self, selector: "backgroundCleanExpiredDiskCache", name: UIApplicationDidEnterBackgroundNotification, object: nil)
  107. #endif
  108. }
  109. deinit {
  110. NSNotificationCenter.defaultCenter().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.
  117. It is an async operation, if you need to do something about the stored image, use `-storeImage:forKey:toDisk:completionHandler:`
  118. instead.
  119. - parameter image: The image will be stored.
  120. - parameter originalData: The original data of the image.
  121. Kingfisher will use it to check the format of the image and optimize cache size on disk.
  122. If `nil` is supplied, the image data will be saved as a normalized PNG file.
  123. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage.
  124. - parameter key: Key for the image.
  125. */
  126. public func storeImage(image: Image, originalData: NSData? = nil, forKey key: String) {
  127. storeImage(image, originalData: originalData, forKey: key, toDisk: true, completionHandler: nil)
  128. }
  129. /**
  130. Store an image to cache. It is an async operation.
  131. - parameter image: The image will be stored.
  132. - parameter originalData: The original data of the image.
  133. Kingfisher will use it to check the format of the image and optimize cache size on disk.
  134. If `nil` is supplied, the image data will be saved as a normalized PNG file.
  135. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage.
  136. - parameter key: Key for the image.
  137. - parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory.
  138. - parameter completionHandler: Called when stroe operation completes.
  139. */
  140. public func storeImage(image: Image, originalData: NSData? = nil, forKey key: String, toDisk: Bool, completionHandler: (() -> ())?) {
  141. memoryCache.setObject(image, forKey: key, cost: image.kf_imageCost)
  142. func callHandlerInMainQueue() {
  143. if let handler = completionHandler {
  144. dispatch_async(dispatch_get_main_queue()) {
  145. handler()
  146. }
  147. }
  148. }
  149. if toDisk {
  150. dispatch_async(ioQueue, { () -> Void in
  151. let imageFormat: ImageFormat
  152. if let originalData = originalData {
  153. imageFormat = originalData.kf_imageFormat
  154. } else {
  155. imageFormat = .Unknown
  156. }
  157. let data: NSData?
  158. switch imageFormat {
  159. case .PNG: data = originalData ?? ImagePNGRepresentation(image)
  160. case .JPEG: data = originalData ?? ImageJPEGRepresentation(image, 1.0)
  161. case .GIF: data = originalData ?? ImageGIFRepresentation(image)
  162. case .Unknown: data = originalData ?? ImagePNGRepresentation(image.kf_normalizedImage())
  163. }
  164. if let data = data {
  165. if !self.fileManager.fileExistsAtPath(self.diskCachePath) {
  166. do {
  167. try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
  168. } catch _ {}
  169. }
  170. self.fileManager.createFileAtPath(self.cachePathForKey(key), contents: data, attributes: nil)
  171. }
  172. callHandlerInMainQueue()
  173. })
  174. } else {
  175. callHandlerInMainQueue()
  176. }
  177. }
  178. /**
  179. Remove the image for key for the cache. It will be opted out from both memory and disk.
  180. It is an async operation, if you need to do something about the stored image, use `-removeImageForKey:fromDisk:completionHandler:`
  181. instead.
  182. - parameter key: Key for the image.
  183. */
  184. public func removeImageForKey(key: String) {
  185. removeImageForKey(key, fromDisk: true, completionHandler: nil)
  186. }
  187. /**
  188. Remove the image for key for the cache. It is an async operation.
  189. - parameter key: Key for the image.
  190. - parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory.
  191. - parameter completionHandler: Called when removal operation completes.
  192. */
  193. public func removeImageForKey(key: String, fromDisk: Bool, completionHandler: (() -> ())?) {
  194. memoryCache.removeObjectForKey(key)
  195. func callHandlerInMainQueue() {
  196. if let handler = completionHandler {
  197. dispatch_async(dispatch_get_main_queue()) {
  198. handler()
  199. }
  200. }
  201. }
  202. if fromDisk {
  203. dispatch_async(ioQueue, { () -> Void in
  204. do {
  205. try self.fileManager.removeItemAtPath(self.cachePathForKey(key))
  206. } catch _ {}
  207. callHandlerInMainQueue()
  208. })
  209. } else {
  210. callHandlerInMainQueue()
  211. }
  212. }
  213. }
  214. // MARK: - Get data from cache
  215. extension ImageCache {
  216. /**
  217. Get an image for a key from memory or disk.
  218. - parameter key: Key for the image.
  219. - parameter options: Options of retrieving image.
  220. - 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`.
  221. - returns: The retrieving task.
  222. */
  223. public func retrieveImageForKey(key: String, options: KingfisherOptionsInfo?, completionHandler: ((Image?, CacheType!) -> ())?) -> RetrieveImageDiskTask? {
  224. // No completion handler. Not start working and early return.
  225. guard let completionHandler = completionHandler else {
  226. return nil
  227. }
  228. var block: RetrieveImageDiskTask?
  229. let options = options ?? KingfisherEmptyOptionsInfo
  230. if let image = self.retrieveImageInMemoryCacheForKey(key) {
  231. dispatch_async_safely_to_queue(options.callbackDispatchQueue) { () -> Void in
  232. completionHandler(image, .Memory)
  233. }
  234. } else {
  235. var sSelf: ImageCache! = self
  236. block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) {
  237. // Begin to load image from disk
  238. if let image = sSelf.retrieveImageInDiskCacheForKey(key, scale: options.scaleFactor) {
  239. if options.backgroundDecode {
  240. dispatch_async(sSelf.processQueue, { () -> Void in
  241. let result = image.kf_decodedImage(scale: options.scaleFactor)
  242. sSelf.storeImage(result!, forKey: key, toDisk: false, completionHandler: nil)
  243. dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in
  244. completionHandler(result, .Memory)
  245. sSelf = nil
  246. })
  247. })
  248. } else {
  249. sSelf.storeImage(image, forKey: key, toDisk: false, completionHandler: nil)
  250. dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in
  251. completionHandler(image, .Disk)
  252. sSelf = nil
  253. })
  254. }
  255. } else {
  256. // No image found from either memory or disk
  257. dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in
  258. completionHandler(nil, nil)
  259. sSelf = nil
  260. })
  261. }
  262. }
  263. dispatch_async(sSelf.ioQueue, block!)
  264. }
  265. return block
  266. }
  267. /**
  268. Get an image for a key from memory.
  269. - parameter key: Key for the image.
  270. - returns: The image object if it is cached, or `nil` if there is no such key in the cache.
  271. */
  272. public func retrieveImageInMemoryCacheForKey(key: String) -> Image? {
  273. return memoryCache.objectForKey(key) as? Image
  274. }
  275. /**
  276. Get an image for a key from disk.
  277. - parameter key: Key for the image.
  278. - param scale: The scale factor to assume when interpreting the image data.
  279. - returns: The image object if it is cached, or `nil` if there is no such key in the cache.
  280. */
  281. public func retrieveImageInDiskCacheForKey(key: String, scale: CGFloat = 1.0) -> Image? {
  282. return diskImageForKey(key, scale: scale)
  283. }
  284. }
  285. // MARK: - Clear & Clean
  286. extension ImageCache {
  287. /**
  288. Clear memory cache.
  289. */
  290. @objc public func clearMemoryCache() {
  291. memoryCache.removeAllObjects()
  292. }
  293. /**
  294. Clear disk cache. This is could be an async or sync operation.
  295. Specify the way you want it by passing the `sync` parameter.
  296. */
  297. public func clearDiskCache() {
  298. clearDiskCacheWithCompletionHandler(nil)
  299. }
  300. /**
  301. Clear disk cache. This is an async operation.
  302. - parameter completionHander: Called after the operation completes.
  303. */
  304. public func clearDiskCacheWithCompletionHandler(completionHander: (()->())?) {
  305. dispatch_async(ioQueue, { () -> Void in
  306. do {
  307. try self.fileManager.removeItemAtPath(self.diskCachePath)
  308. try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
  309. } catch _ {
  310. }
  311. if let completionHander = completionHander {
  312. dispatch_async(dispatch_get_main_queue(), { () -> Void in
  313. completionHander()
  314. })
  315. }
  316. })
  317. }
  318. /**
  319. Clean expired disk cache. This is an async operation.
  320. */
  321. @objc public func cleanExpiredDiskCache() {
  322. cleanExpiredDiskCacheWithCompletionHander(nil)
  323. }
  324. /**
  325. Clean expired disk cache. This is an async operation.
  326. - parameter completionHandler: Called after the operation completes.
  327. */
  328. public func cleanExpiredDiskCacheWithCompletionHander(completionHandler: (()->())?) {
  329. // Do things in cocurrent io queue
  330. dispatch_async(ioQueue, { () -> Void in
  331. var (URLsToDelete, diskCacheSize, cachedFiles) = self.travelCachedFiles(onlyForCacheSize: false)
  332. for fileURL in URLsToDelete {
  333. do {
  334. try self.fileManager.removeItemAtURL(fileURL)
  335. } catch _ {
  336. }
  337. }
  338. if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize {
  339. let targetSize = self.maxDiskCacheSize / 2
  340. // Sort files by last modify date. We want to clean from the oldest files.
  341. let sortedFiles = cachedFiles.keysSortedByValue {
  342. resourceValue1, resourceValue2 -> Bool in
  343. if let date1 = resourceValue1[NSURLContentModificationDateKey] as? NSDate,
  344. date2 = resourceValue2[NSURLContentModificationDateKey] as? NSDate {
  345. return date1.compare(date2) == .OrderedAscending
  346. }
  347. // Not valid date information. This should not happen. Just in case.
  348. return true
  349. }
  350. for fileURL in sortedFiles {
  351. do {
  352. try self.fileManager.removeItemAtURL(fileURL)
  353. } catch {
  354. }
  355. URLsToDelete.append(fileURL)
  356. if let fileSize = cachedFiles[fileURL]?[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
  357. diskCacheSize -= fileSize.unsignedLongValue
  358. }
  359. if diskCacheSize < targetSize {
  360. break
  361. }
  362. }
  363. }
  364. dispatch_async(dispatch_get_main_queue(), { () -> Void in
  365. if URLsToDelete.count != 0 {
  366. let cleanedHashes = URLsToDelete.map({ (url) -> String in
  367. return url.lastPathComponent!
  368. })
  369. NSNotificationCenter.defaultCenter().postNotificationName(KingfisherDidCleanDiskCacheNotification, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
  370. }
  371. completionHandler?()
  372. })
  373. })
  374. }
  375. private func travelCachedFiles(onlyForCacheSize onlyForCacheSize: Bool) -> (URLsToDelete: [NSURL], diskCacheSize: UInt, cachedFiles: [NSURL: [NSObject: AnyObject]]) {
  376. let diskCacheURL = NSURL(fileURLWithPath: diskCachePath)
  377. let resourceKeys = [NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]
  378. let expiredDate = NSDate(timeIntervalSinceNow: -self.maxCachePeriodInSecond)
  379. var cachedFiles = [NSURL: [NSObject: AnyObject]]()
  380. var URLsToDelete = [NSURL]()
  381. var diskCacheSize: UInt = 0
  382. if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil),
  383. urls = fileEnumerator.allObjects as? [NSURL] {
  384. for fileURL in urls {
  385. do {
  386. let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys)
  387. // If it is a Directory. Continue to next file URL.
  388. if let isDirectory = resourceValues[NSURLIsDirectoryKey] as? NSNumber {
  389. if isDirectory.boolValue {
  390. continue
  391. }
  392. }
  393. if !onlyForCacheSize {
  394. // If this file is expired, add it to URLsToDelete
  395. if let modificationDate = resourceValues[NSURLContentModificationDateKey] as? NSDate {
  396. if modificationDate.laterDate(expiredDate) == expiredDate {
  397. URLsToDelete.append(fileURL)
  398. continue
  399. }
  400. }
  401. }
  402. if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
  403. diskCacheSize += fileSize.unsignedLongValue
  404. if !onlyForCacheSize {
  405. cachedFiles[fileURL] = resourceValues
  406. }
  407. }
  408. } catch _ {
  409. }
  410. }
  411. }
  412. return (URLsToDelete, diskCacheSize, cachedFiles)
  413. }
  414. #if !os(OSX) && !os(watchOS)
  415. /**
  416. Clean expired disk cache when app in background. This is an async operation.
  417. In most cases, you should not call this method explicitly.
  418. It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
  419. */
  420. @objc public func backgroundCleanExpiredDiskCache() {
  421. func endBackgroundTask(inout task: UIBackgroundTaskIdentifier) {
  422. UIApplication.sharedApplication().endBackgroundTask(task)
  423. task = UIBackgroundTaskInvalid
  424. }
  425. var backgroundTask: UIBackgroundTaskIdentifier!
  426. backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { () -> Void in
  427. endBackgroundTask(&backgroundTask!)
  428. }
  429. cleanExpiredDiskCacheWithCompletionHander { () -> () in
  430. endBackgroundTask(&backgroundTask!)
  431. }
  432. }
  433. #endif
  434. }
  435. // MARK: - Check cache status
  436. extension ImageCache {
  437. /**
  438. * Cache result for checking whether an image is cached for a key.
  439. */
  440. public struct CacheCheckResult {
  441. public let cached: Bool
  442. public let cacheType: CacheType?
  443. }
  444. /**
  445. Check whether an image is cached for a key.
  446. - parameter key: Key for the image.
  447. - returns: The check result.
  448. */
  449. public func isImageCachedForKey(key: String) -> CacheCheckResult {
  450. if memoryCache.objectForKey(key) != nil {
  451. return CacheCheckResult(cached: true, cacheType: .Memory)
  452. }
  453. let filePath = cachePathForKey(key)
  454. var diskCached = false
  455. dispatch_sync(ioQueue) { () -> Void in
  456. diskCached = self.fileManager.fileExistsAtPath(filePath)
  457. }
  458. if diskCached {
  459. return CacheCheckResult(cached: true, cacheType: .Disk)
  460. }
  461. return CacheCheckResult(cached: false, cacheType: nil)
  462. }
  463. /**
  464. Get the hash for the key. This could be used for matching files.
  465. - parameter key: The key which is used for caching.
  466. - returns: Corresponding hash.
  467. */
  468. public func hashForKey(key: String) -> String {
  469. return cacheFileNameForKey(key)
  470. }
  471. /**
  472. Calculate the disk size taken by cache.
  473. It is the total allocated size of the cached files in bytes.
  474. - parameter completionHandler: Called with the calculated size when finishes.
  475. */
  476. public func calculateDiskCacheSizeWithCompletionHandler(completionHandler: ((size: UInt) -> ())) {
  477. dispatch_async(ioQueue, { () -> Void in
  478. let (_, diskCacheSize, _) = self.travelCachedFiles(onlyForCacheSize: true)
  479. dispatch_async(dispatch_get_main_queue(), { () -> Void in
  480. completionHandler(size: diskCacheSize)
  481. })
  482. })
  483. }
  484. /**
  485. Get the cache path for the key.
  486. It is useful for projects with UIWebView or anyone that needs access to the local file path.
  487. i.e. `<img src='path_for_key'>`
  488. - Note: This method does not guarantee there is an image already cached in the path.
  489. You could use `isImageCachedForKey` method to check whether the image is cached under that key.
  490. */
  491. public func cachePathForKey(key: String) -> String {
  492. let fileName = cacheFileNameForKey(key)
  493. return (diskCachePath as NSString).stringByAppendingPathComponent(fileName)
  494. }
  495. }
  496. // MARK: - Internal Helper
  497. extension ImageCache {
  498. func diskImageForKey(key: String, scale: CGFloat) -> Image? {
  499. if let data = diskImageDataForKey(key) {
  500. return Image.kf_imageWithData(data, scale: scale)
  501. } else {
  502. return nil
  503. }
  504. }
  505. func diskImageDataForKey(key: String) -> NSData? {
  506. let filePath = cachePathForKey(key)
  507. return NSData(contentsOfFile: filePath)
  508. }
  509. func cacheFileNameForKey(key: String) -> String {
  510. return key.kf_MD5
  511. }
  512. }
  513. extension Image {
  514. var kf_imageCost: Int {
  515. return kf_images == nil ?
  516. Int(size.height * size.width * kf_scale * kf_scale) :
  517. Int(size.height * size.width * kf_scale * kf_scale) * kf_images!.count
  518. }
  519. }
  520. extension Dictionary {
  521. func keysSortedByValue(isOrderedBefore: (Value, Value) -> Bool) -> [Key] {
  522. return Array(self).sort{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 }
  523. }
  524. }