ImageCache.swift 21 KB

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