ImageCache.swift 29 KB

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