KingfisherManager.swift 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. //
  2. // KingfisherManager.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  6. //
  7. // Copyright (c) 2016 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. #if os(macOS)
  27. import AppKit
  28. #else
  29. import UIKit
  30. #endif
  31. public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> ())
  32. public typealias CompletionHandler = ((_ image: Image?, _ error: NSError?, _ cacheType: CacheType, _ imageURL: URL?) -> ())
  33. /// RetrieveImageTask represents a task of image retrieving process.
  34. /// It contains an async task of getting image from disk and from network.
  35. public class RetrieveImageTask {
  36. static let emptyTask = RetrieveImageTask()
  37. // If task is canceled before the download task started (which means the `downloadTask` is nil),
  38. // the download task should not begin.
  39. var cancelledBeforeDownloadStarting: Bool = false
  40. /// The disk retrieve task in this image task. Kingfisher will try to look up in cache first. This task represent the cache search task.
  41. public var diskRetrieveTask: RetrieveImageDiskTask?
  42. /// The network retrieve task in this image task.
  43. public var downloadTask: RetrieveImageDownloadTask?
  44. /**
  45. Cancel current task. If this task does not begin or already done, do nothing.
  46. */
  47. public func cancel() {
  48. // From Xcode 7 beta 6, the `dispatch_block_cancel` will crash at runtime.
  49. // It fixed in Xcode 7.1.
  50. // See https://github.com/onevcat/Kingfisher/issues/99 for more.
  51. if let diskRetrieveTask = diskRetrieveTask {
  52. diskRetrieveTask.cancel()
  53. }
  54. if let downloadTask = downloadTask {
  55. downloadTask.cancel()
  56. } else {
  57. cancelledBeforeDownloadStarting = true
  58. }
  59. }
  60. }
  61. /// Error domain of Kingfisher
  62. public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error"
  63. /// Main manager class of Kingfisher. It connects Kingfisher downloader and cache.
  64. /// You can use this class to retrieve an image via a specified URL from web or cache.
  65. public class KingfisherManager {
  66. /// Shared manager used by the extensions across Kingfisher.
  67. public static let shared = KingfisherManager()
  68. /// Cache used by this manager
  69. public var cache: ImageCache
  70. /// Downloader used by this manager
  71. public var downloader: ImageDownloader
  72. convenience init() {
  73. self.init(downloader: .default, cache: .default)
  74. }
  75. init(downloader: ImageDownloader, cache: ImageCache) {
  76. self.downloader = downloader
  77. self.cache = cache
  78. }
  79. /**
  80. Get an image with resource.
  81. If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
  82. If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`.
  83. These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
  84. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
  85. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  86. - parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
  87. - parameter completionHandler: Called when the whole retrieving process finished.
  88. - returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
  89. */
  90. @discardableResult
  91. public func retrieveImage(with resource: Resource,
  92. options: KingfisherOptionsInfo?,
  93. progressBlock: DownloadProgressBlock?,
  94. completionHandler: CompletionHandler?) -> RetrieveImageTask
  95. {
  96. let task = RetrieveImageTask()
  97. if let options = options, options.forceRefresh {
  98. _ = downloadAndCacheImage(
  99. with: resource.downloadURL,
  100. forKey: resource.cacheKey,
  101. retrieveImageTask: task,
  102. progressBlock: progressBlock,
  103. completionHandler: completionHandler,
  104. options: options)
  105. } else {
  106. tryToRetrieveImageFromCache(
  107. forKey: resource.cacheKey,
  108. with: resource.downloadURL,
  109. retrieveImageTask: task,
  110. progressBlock: progressBlock,
  111. completionHandler: completionHandler,
  112. options: options)
  113. }
  114. return task
  115. }
  116. @discardableResult
  117. func downloadAndCacheImage(with url: URL,
  118. forKey key: String,
  119. retrieveImageTask: RetrieveImageTask,
  120. progressBlock: DownloadProgressBlock?,
  121. completionHandler: CompletionHandler?,
  122. options: KingfisherOptionsInfo?) -> RetrieveImageDownloadTask?
  123. {
  124. let options = options ?? KingfisherEmptyOptionsInfo
  125. let downloader = options.downloader
  126. return downloader.downloadImage(with: url, retrieveImageTask: retrieveImageTask, options: options,
  127. progressBlock: { receivedSize, totalSize in
  128. progressBlock?(receivedSize, totalSize)
  129. },
  130. completionHandler: { image, error, imageURL, originalData in
  131. let targetCache = options.targetCache
  132. if let error = error, error.code == KingfisherError.notModified.rawValue {
  133. // Not modified. Try to find the image from cache.
  134. // (The image should be in cache. It should be guaranteed by the framework users.)
  135. targetCache.retrieveImage(forKey: key, options: options, completionHandler: { (cacheImage, cacheType) -> () in
  136. completionHandler?(cacheImage, nil, cacheType, url)
  137. })
  138. return
  139. }
  140. if let image = image, let originalData = originalData {
  141. targetCache.store(image,
  142. original: originalData,
  143. forKey: key,
  144. processorIdentifier:options.processor.identifier,
  145. cacheSerializer: options.cacheSerializer,
  146. toDisk: !options.cacheMemoryOnly,
  147. completionHandler: nil)
  148. }
  149. completionHandler?(image, error, .none, url)
  150. })
  151. }
  152. func tryToRetrieveImageFromCache(forKey key: String,
  153. with url: URL,
  154. retrieveImageTask: RetrieveImageTask,
  155. progressBlock: DownloadProgressBlock?,
  156. completionHandler: CompletionHandler?,
  157. options: KingfisherOptionsInfo?)
  158. {
  159. let diskTaskCompletionHandler: CompletionHandler = { (image, error, cacheType, imageURL) -> () in
  160. // Break retain cycle created inside diskTask closure below
  161. retrieveImageTask.diskRetrieveTask = nil
  162. completionHandler?(image, error, cacheType, imageURL)
  163. }
  164. let targetCache = options?.targetCache ?? cache
  165. let diskTask = targetCache.retrieveImage(forKey: key, options: options,
  166. completionHandler: { image, cacheType in
  167. if image != nil {
  168. diskTaskCompletionHandler(image, nil, cacheType, url)
  169. } else if let options = options, options.onlyFromCache {
  170. let error = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notCached.rawValue, userInfo: nil)
  171. diskTaskCompletionHandler(nil, error, .none, url)
  172. } else {
  173. self.downloadAndCacheImage(
  174. with: url,
  175. forKey: key,
  176. retrieveImageTask: retrieveImageTask,
  177. progressBlock: progressBlock,
  178. completionHandler: diskTaskCompletionHandler,
  179. options: options)
  180. }
  181. }
  182. )
  183. retrieveImageTask.diskRetrieveTask = diskTask
  184. }
  185. }