ImageCache.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. //
  2. // ImageCache.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  6. //
  7. // Copyright (c) 2018 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. extension Notification.Name {
  32. /// This notification will be sent when the disk cache got cleaned either there are cached files expired or the
  33. /// total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger
  34. /// this notification.
  35. ///
  36. /// The `object` of this notification is the `ImageCache` object which sends the notification.
  37. /// A list of removed hashes (files) could be retrieved by accessing the array under
  38. /// `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received.
  39. /// By checking the array, you could know the hash codes of files are removed.
  40. public static let KingfisherDidCleanDiskCache =
  41. Notification.Name("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache")
  42. }
  43. /// Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`.
  44. public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash"
  45. /// Cache type of a cached image.
  46. /// - none: The image is not cached yet when retrieving it.
  47. /// - memory: The image is cached in memory.
  48. /// - disk: The image is cached in disk.
  49. public enum CacheType {
  50. case none, memory, disk
  51. public var cached: Bool {
  52. switch self {
  53. case .memory, .disk: return true
  54. case .none: return false
  55. }
  56. }
  57. }
  58. public struct CacheStoreResult {
  59. let memoryCacheResult: Result<()>
  60. let diskCacheResult: Result<()>
  61. }
  62. extension Image: CacheCostCalculatable {
  63. public var cacheCost: Int { return kf.cost }
  64. }
  65. extension Data: DataTransformable {
  66. public func toData() throws -> Data {
  67. return self
  68. }
  69. public static func fromData(_ data: Data) throws -> Data {
  70. return data
  71. }
  72. public static let empty = Data()
  73. }
  74. public enum ImageCacheResult {
  75. case disk(Image)
  76. case memory(Image)
  77. case none
  78. public var image: Image? {
  79. switch self {
  80. case .disk(let image): return image
  81. case .memory(let image): return image
  82. case .none: return nil
  83. }
  84. }
  85. public var cacheType: CacheType {
  86. switch self {
  87. case .disk: return .disk
  88. case .memory: return .memory
  89. case .none: return .none
  90. }
  91. }
  92. }
  93. /// `ImageCache` represents both the memory and disk cache system of Kingfisher.
  94. /// While a default image cache object will be used if you prefer the extension methods of Kingfisher,
  95. /// you can create your own cache object and configure it as your need. You could use an `ImageCache`
  96. /// object to manipulate memory and disk cache for Kingfisher.
  97. open class ImageCache {
  98. public let memoryStorage: MemoryStorage<Image>
  99. public let diskStorage: DiskStorage<Data>
  100. //Disk
  101. fileprivate let ioQueue: DispatchQueue
  102. /// The default cache.
  103. public static let `default` = ImageCache(name: "default")
  104. /// Closure that defines the disk cache path from a given path and cacheName.
  105. public typealias DiskCachePathClosure = (URL, String) -> URL
  106. public convenience init(name: String) {
  107. try! self.init(name: name, path: nil, diskCachePathClosure: nil)
  108. }
  109. /**
  110. Init method. Passing a name for the cache. It represents a cache folder in the memory and disk.
  111. - parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name
  112. appending to the cache path. This value should not be an empty string.
  113. - parameter path: Optional - Location of cache path on disk. If `nil` is passed in (the default value),
  114. the `.cachesDirectory` in of your app will be used.
  115. - parameter diskCachePathClosure: Closure that takes in an optional initial path string and generates
  116. the final disk cache path. You could use it to fully customize your cache path.
  117. */
  118. public init(name: String,
  119. path: String?,
  120. diskCachePathClosure: DiskCachePathClosure? = nil) throws
  121. {
  122. if name.isEmpty {
  123. fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
  124. }
  125. let cacheName = "com.onevcat.Kingfisher.ImageCache.\(name)"
  126. let totalMemory = ProcessInfo.processInfo.physicalMemory
  127. let costLimit = totalMemory / 4
  128. memoryStorage = MemoryStorage(config: .init(totalCostLimit: costLimit > .max ? .max : Int(costLimit)))
  129. var diskConfig = DiskStorage<Data>.Config(
  130. name: name,
  131. directory: path.flatMap { URL(string: $0) },
  132. sizeLimit: 0)
  133. if let closure = diskCachePathClosure {
  134. diskConfig.cachePathBlock = diskCachePathClosure
  135. defer { diskConfig.cachePathBlock = nil }
  136. }
  137. diskStorage = try DiskStorage(config: diskConfig)
  138. let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(name)"
  139. ioQueue = DispatchQueue(label: ioQueueName)
  140. #if !os(macOS) && !os(watchOS)
  141. NotificationCenter.default.addObserver(
  142. self, selector: #selector(clearMemoryCache), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
  143. NotificationCenter.default.addObserver(
  144. self, selector: #selector(cleanExpiredDiskCache), name: UIApplication.willTerminateNotification, object: nil)
  145. NotificationCenter.default.addObserver(
  146. self, selector: #selector(backgroundCleanExpiredDiskCache), name: UIApplication.didEnterBackgroundNotification, object: nil)
  147. #endif
  148. }
  149. deinit {
  150. NotificationCenter.default.removeObserver(self)
  151. }
  152. // MARK: - Store & Remove
  153. /**
  154. Store an image to cache. It will be saved to both memory and disk. It is an async operation.
  155. - parameter image: The image to be stored.
  156. - parameter original: The original data of the image.
  157. Kingfisher will use it to check the format of the image and optimize cache size on disk.
  158. If `nil` is supplied, the image data will be saved as a normalized PNG file.
  159. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage.
  160. - parameter key: Key for the image.
  161. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of
  162. processor to it.
  163. This identifier will be used to generate a corresponding key for the combination of `key` and processor.
  164. - parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory.
  165. - parameter completionHandler: Called when store operation completes.
  166. */
  167. open func store(_ image: Image,
  168. original: Data? = nil,
  169. forKey key: String,
  170. processorIdentifier identifier: String = "",
  171. cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
  172. toDisk: Bool = true,
  173. callbackQueue: CallbackQueue = .untouch,
  174. completionHandler: ((CacheStoreResult) -> Void)? = nil)
  175. {
  176. let computedKey = key.computedKey(with: identifier)
  177. // Memory storage should not throw.
  178. memoryStorage.storeNoThrow(value: image, forKey: computedKey)
  179. if toDisk {
  180. ioQueue.async {
  181. let result: CacheStoreResult
  182. if let data = serializer.data(with: image, original: original) {
  183. do {
  184. try self.diskStorage.store(value: data, forKey: computedKey)
  185. result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(()))
  186. } catch {
  187. let diskError = KingfisherError.cacheError(
  188. reason: .cannotConvertToData(object: data, error: error))
  189. result = CacheStoreResult(
  190. memoryCacheResult: .success(()),
  191. diskCacheResult: .failure(diskError)
  192. )
  193. }
  194. } else {
  195. let diskError = KingfisherError.cacheError(
  196. reason: .cannotSerializeImage(image: image, original: original, serializer: serializer))
  197. result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .failure(diskError))
  198. }
  199. if let completionHandler = completionHandler {
  200. callbackQueue.execute { completionHandler(result) }
  201. }
  202. }
  203. } else {
  204. if let completionHandler = completionHandler {
  205. let result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(()))
  206. callbackQueue.execute { completionHandler(result) }
  207. }
  208. }
  209. }
  210. /**
  211. Remove the image for key for the cache. It will be opted out from both memory and disk.
  212. It is an async operation.
  213. - parameter key: Key for the image.
  214. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it.
  215. This identifier will be used to generate a corresponding key for the combination of `key` and processor.
  216. - parameter fromMemory: Whether this image should be removed from memory or not. If false, the image won't be removed from memory.
  217. - parameter fromDisk: Whether this image should be removed from disk or not. If false, the image won't be removed from disk.
  218. - parameter completionHandler: Called when removal operation completes.
  219. */
  220. open func removeImage(forKey key: String,
  221. processorIdentifier identifier: String = "",
  222. fromMemory: Bool = true,
  223. fromDisk: Bool = true,
  224. completionHandler: (() -> Void)? = nil)
  225. {
  226. let computedKey = key.computedKey(with: identifier)
  227. if fromMemory {
  228. try? memoryStorage.remove(forKey: computedKey)
  229. }
  230. if fromDisk {
  231. ioQueue.async{
  232. try? self.diskStorage.remove(forKey: computedKey)
  233. completionHandler?()
  234. }
  235. } else {
  236. completionHandler?()
  237. }
  238. }
  239. // MARK: - Get data from cache
  240. /**
  241. Get an image for a key from memory or disk.
  242. - parameter key: Key for the image.
  243. - parameter options: Options of retrieving image. If you need to retrieve an image which was
  244. stored with a specified `ImageProcessor`, pass the processor in the option too.
  245. - parameter completionHandler: Called when getting operation completes with image result and cached type of
  246. this image. If there is no such key cached, the image will be `nil`.
  247. - returns: The retrieving task.
  248. */
  249. open func retrieveImage(forKey key: String,
  250. options: KingfisherOptionsInfo? = nil,
  251. callbackQueue: CallbackQueue = .untouch,
  252. completionHandler: ((Result<(ImageCacheResult)>) -> Void)?)
  253. {
  254. // No completion handler. Not start working and early return.
  255. guard let completionHandler = completionHandler else { return }
  256. let options = options ?? .empty
  257. let imageModifier = options.imageModifier
  258. if let image = retrieveImageInMemoryCache(forKey: key, options: options) {
  259. let image = imageModifier.modify(image)
  260. callbackQueue.execute { completionHandler(.success(.memory(image))) }
  261. } else if options.fromMemoryCacheOrRefresh {
  262. callbackQueue.execute { completionHandler(.success(.none)) }
  263. } else {
  264. ioQueue.async {
  265. self.retrieveImageInDiskCache(forKey: key, options: options, callbackQueue: callbackQueue) {
  266. result in
  267. // The callback queue is already correct in this closure.
  268. switch result {
  269. case .success(let image):
  270. guard let image = imageModifier.modify(image) else {
  271. // No image found in disk storage.
  272. completionHandler(.success(.none))
  273. return
  274. }
  275. // Cache the disk image to memory.
  276. // Memory cache does not change callback queue, which is already which we want.
  277. self.store(
  278. image,
  279. forKey: key,
  280. processorIdentifier: options.processor.identifier,
  281. cacheSerializer: options.cacheSerializer,
  282. toDisk: false)
  283. {
  284. _ in
  285. completionHandler(.success(.disk(image)))
  286. }
  287. case .failure(let error):
  288. completionHandler(.failure(error))
  289. }
  290. }
  291. }
  292. }
  293. }
  294. /**
  295. Get an image for a key from memory.
  296. - parameter key: Key for the image.
  297. - parameter options: Options of retrieving image. If you need to retrieve an image which was
  298. stored with a specified `ImageProcessor`, pass the processor in the option too.
  299. - returns: The image object if it is cached, or `nil` if there is no such key in the cache.
  300. */
  301. open func retrieveImageInMemoryCache(
  302. forKey key: String,
  303. options: KingfisherOptionsInfo? = nil) -> Image?
  304. {
  305. let options = options ?? .empty
  306. let computedKey = key.computedKey(with: options.processor.identifier)
  307. do {
  308. return try memoryStorage.value(forKey: computedKey)
  309. } catch {
  310. return nil
  311. }
  312. }
  313. open func retrieveImageInDiskCache(
  314. forKey key: String,
  315. options: KingfisherOptionsInfo? = nil,
  316. callbackQueue: CallbackQueue = .untouch,
  317. completionHandler: @escaping (Result<Image?>) -> Void)
  318. {
  319. let options = options ?? .empty
  320. let computedKey = key.computedKey(with: options.processor.identifier)
  321. ioQueue.async {
  322. do {
  323. var image: Image? = nil
  324. if let data = try self.diskStorage.value(forKey: computedKey) {
  325. image = options.cacheSerializer.image(with: data, options: options)
  326. }
  327. callbackQueue.execute { completionHandler(.success(image)) }
  328. } catch {
  329. callbackQueue.execute { completionHandler(.failure(error)) }
  330. }
  331. }
  332. }
  333. // MARK: - Clear & Clean
  334. /**
  335. Clear memory cache.
  336. */
  337. @objc public func clearMemoryCache() {
  338. try? memoryStorage.removeAll()
  339. }
  340. /**
  341. Clear disk cache. This is an async operation.
  342. - parameter completionHander: Called after the operation completes.
  343. */
  344. open func clearDiskCache(completion handler: (()->())? = nil) {
  345. ioQueue.async {
  346. do {
  347. try self.diskStorage.removeAll()
  348. } catch _ { }
  349. handler?()
  350. }
  351. }
  352. /**
  353. Clean expired disk cache. This is an async operation.
  354. */
  355. @objc fileprivate func cleanExpiredDiskCache() {
  356. cleanExpiredDiskCache(completion: nil)
  357. }
  358. /**
  359. Clean expired disk cache. This is an async operation.
  360. - parameter completionHandler: Called after the operation completes.
  361. */
  362. open func cleanExpiredDiskCache(completion handler: (() -> Void)? = nil) {
  363. ioQueue.async {
  364. do {
  365. var removed: [URL] = []
  366. let removedExpired = try self.diskStorage.removeExpiredValues()
  367. removed.append(contentsOf: removedExpired)
  368. let removedSizeExceeded = try self.diskStorage.removeSizeExceededValues()
  369. removed.append(contentsOf: removedSizeExceeded)
  370. if !removed.isEmpty {
  371. DispatchQueue.main.async {
  372. let cleanedHashes = removed.map { $0.lastPathComponent }
  373. NotificationCenter.default.post(
  374. name: .KingfisherDidCleanDiskCache,
  375. object: self,
  376. userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
  377. }
  378. }
  379. handler?()
  380. } catch {}
  381. }
  382. }
  383. #if !os(macOS) && !os(watchOS)
  384. /**
  385. Clean expired disk cache when app in background. This is an async operation.
  386. In most cases, you should not call this method explicitly.
  387. It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
  388. */
  389. @objc public func backgroundCleanExpiredDiskCache() {
  390. // if 'sharedApplication()' is unavailable, then return
  391. guard let sharedApplication = KingfisherClass<UIApplication>.shared else { return }
  392. func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) {
  393. sharedApplication.endBackgroundTask(task)
  394. task = UIBackgroundTaskIdentifier.invalid
  395. }
  396. var backgroundTask: UIBackgroundTaskIdentifier!
  397. backgroundTask = sharedApplication.beginBackgroundTask {
  398. endBackgroundTask(&backgroundTask!)
  399. }
  400. cleanExpiredDiskCache {
  401. endBackgroundTask(&backgroundTask!)
  402. }
  403. }
  404. #endif
  405. // MARK: - Check cache status
  406. /// Cache type for checking whether an image is cached for a key in current cache.
  407. ///
  408. /// - Parameters:
  409. /// - key: Key for the image.
  410. /// - identifier: Processor identifier which used for this image. Default is empty string.
  411. /// - Returns: A `CacheType` instance which indicates the cache status. `.none` means the image is not in cache yet.
  412. open func imageCachedType(forKey key: String, processorIdentifier identifier: String = "") -> CacheType {
  413. let computedKey = key.computedKey(with: identifier)
  414. if memoryStorage.isCached(forKey: computedKey) { return .memory }
  415. if diskStorage.isCached(forKey: computedKey) { return .disk }
  416. return .none
  417. }
  418. /**
  419. Get the hash for the key. This could be used for matching files.
  420. - parameter key: The key which is used for caching.
  421. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it.
  422. - returns: Corresponding hash.
  423. */
  424. open func hash(forKey key: String, processorIdentifier identifier: String = "") -> String {
  425. let computedKey = key.computedKey(with: identifier)
  426. return diskStorage.cacheFileName(forKey: computedKey)
  427. }
  428. /**
  429. Calculate the disk size taken by cache.
  430. It is the total allocated size of the cached files in bytes.
  431. - parameter completionHandler: Called with the calculated size when finishes.
  432. */
  433. open func calculateDiskCacheSize(completion handler: @escaping ((Result<UInt>) -> Void)) {
  434. ioQueue.async {
  435. do {
  436. let size = try self.diskStorage.totalSize()
  437. DispatchQueue.main.async {
  438. handler(.success(size))
  439. }
  440. } catch {
  441. handler(.failure(error))
  442. }
  443. }
  444. }
  445. /**
  446. Get the cache path for the key.
  447. It is useful for projects with UIWebView or anyone that needs access to the local file path.
  448. i.e. Replace the `<img src='path_for_key'>` tag in your HTML.
  449. - Note: This method does not guarantee there is an image already cached in the path. It just returns the path
  450. that the image should be.
  451. You could use `isImageCached(forKey:)` method to check whether the image is cached under that key.
  452. */
  453. open func cachePath(forKey key: String, processorIdentifier identifier: String = "") -> String {
  454. let computedKey = key.computedKey(with: identifier)
  455. return diskStorage.cacheFileURL(forKey: computedKey).absoluteString
  456. }
  457. }
  458. extension Dictionary {
  459. func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] {
  460. return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 }
  461. }
  462. }
  463. #if !os(macOS) && !os(watchOS)
  464. // MARK: - For App Extensions
  465. extension UIApplication: KingfisherClassCompatible { }
  466. extension KingfisherClass where Base: UIApplication {
  467. public static var shared: UIApplication? {
  468. let selector = NSSelectorFromString("sharedApplication")
  469. guard Base.responds(to: selector) else { return nil }
  470. return Base.perform(selector).takeUnretainedValue() as? UIApplication
  471. }
  472. }
  473. #endif
  474. extension String {
  475. func computedKey(with identifier: String) -> String {
  476. if identifier.isEmpty {
  477. return self
  478. } else {
  479. return appending("@\(identifier)")
  480. }
  481. }
  482. }