ImagePrefetcher.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. //
  2. // ImagePrefetcher.swift
  3. // Kingfisher
  4. //
  5. // Created by Claire Knight <claire.knight@moggytech.co.uk> on 24/02/2016
  6. //
  7. // Copyright (c) 2019 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. /// Progress update block of prefetcher.
  32. ///
  33. /// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
  34. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while
  35. /// downloading, encountered an error when downloading or the download not being started at all.
  36. /// - `completedResources`: An array of resources that are downloaded and cached successfully.
  37. public typealias PrefetcherProgressBlock =
  38. ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void)
  39. public typealias PrefetcherSourceProgressBlock =
  40. ((_ skippedSources: [Source], _ failedSources: [Source], _ completedSources: [Source]) -> Void)
  41. /// Completion block of prefetcher.
  42. ///
  43. /// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
  44. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while
  45. /// downloading, encountered an error when downloading or the download not being started at all.
  46. /// - `completedResources`: An array of resources that are downloaded and cached successfully.
  47. public typealias PrefetcherCompletionHandler =
  48. ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void)
  49. public typealias PrefetcherSourceCompletionHandler =
  50. ((_ skippedSources: [Source], _ failedSources: [Source], _ completedSources: [Source]) -> Void)
  51. /// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them.
  52. /// This is useful when you know a list of image resources and want to download them before showing. It also works with
  53. /// some Cocoa prefetching mechanism like table view or collection view `prefetchDataSource`, to start image downloading
  54. /// and caching before they display on screen.
  55. public class ImagePrefetcher {
  56. /// The maximum concurrent downloads to use when prefetching images. Default is 5.
  57. public var maxConcurrentDownloads = 5
  58. private let prefetchResources: [Resource]
  59. private let optionsInfo: KingfisherParsedOptionsInfo
  60. private var progressBlock: PrefetcherProgressBlock?
  61. private var completionHandler: PrefetcherCompletionHandler?
  62. private var tasks = [URL: DownloadTask.WrappedTask]()
  63. private var pendingResources: ArraySlice<Resource>
  64. private var skippedResources = [Resource]()
  65. private var completedResources = [Resource]()
  66. private var failedResources = [Resource]()
  67. private var stopped = false
  68. // A manager used for prefetching. We will use the helper methods in manager.
  69. private let manager: KingfisherManager
  70. private var finished: Bool {
  71. let totalFinished: Int = failedResources.count + skippedResources.count + completedResources.count
  72. return totalFinished == prefetchResources.count && tasks.isEmpty
  73. }
  74. /// Creates an image prefetcher with an array of URLs.
  75. ///
  76. /// The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable.
  77. /// After you get a valid `ImagePrefetcher` object, you call `start()` on it to begin the prefetching process.
  78. /// The images which are already cached will be skipped without downloading again.
  79. ///
  80. /// - Parameters:
  81. /// - urls: The URLs which should be prefetched.
  82. /// - options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  83. /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled.
  84. /// - completionHandler: Called when the whole prefetching process finished.
  85. ///
  86. /// - Note:
  87. /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
  88. /// the downloader and cache target respectively. You can specify another downloader or cache by using
  89. /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in
  90. /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method.
  91. public convenience init(urls: [URL],
  92. options: KingfisherOptionsInfo? = nil,
  93. progressBlock: PrefetcherProgressBlock? = nil,
  94. completionHandler: PrefetcherCompletionHandler? = nil)
  95. {
  96. let resources: [Resource] = urls.map { $0 }
  97. self.init(
  98. resources: resources,
  99. options: options,
  100. progressBlock: progressBlock,
  101. completionHandler: completionHandler)
  102. }
  103. /// Creates an image prefetcher with an array of resources.
  104. ///
  105. /// - Parameters:
  106. /// - resources: The resources which should be prefetched. See `Resource` type for more.
  107. /// - options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  108. /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled.
  109. /// - completionHandler: Called when the whole prefetching process finished.
  110. ///
  111. /// - Note:
  112. /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
  113. /// the downloader and cache target respectively. You can specify another downloader or cache by using
  114. /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in
  115. /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method.
  116. public init(resources: [Resource],
  117. options: KingfisherOptionsInfo? = nil,
  118. progressBlock: PrefetcherProgressBlock? = nil,
  119. completionHandler: PrefetcherCompletionHandler? = nil)
  120. {
  121. var options = KingfisherParsedOptionsInfo(options)
  122. prefetchResources = resources
  123. pendingResources = ArraySlice(resources)
  124. // We want all callbacks from our prefetch queue, so we should ignore the callback queue in options.
  125. // Add our own callback dispatch queue to make sure all internal callbacks are
  126. // coming back in our expected queue.
  127. options.callbackQueue = .untouch
  128. optionsInfo = options
  129. let cache = optionsInfo.targetCache ?? .default
  130. let downloader = optionsInfo.downloader ?? .default
  131. manager = KingfisherManager(downloader: downloader, cache: cache)
  132. self.progressBlock = progressBlock
  133. self.completionHandler = completionHandler
  134. }
  135. /// Starts to download the resources and cache them. This can be useful for background downloading
  136. /// of assets that are required for later use in an app. This code will not try and update any UI
  137. /// with the results of the process.
  138. public func start() {
  139. guard !stopped else {
  140. assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.")
  141. handleComplete()
  142. return
  143. }
  144. guard maxConcurrentDownloads > 0 else {
  145. assertionFailure("There should be concurrent downloads value should be at least 1.")
  146. handleComplete()
  147. return
  148. }
  149. // Empty case.
  150. guard prefetchResources.count > 0 else {
  151. handleComplete()
  152. return
  153. }
  154. let initialConcurrentDownloads = min(prefetchResources.count, maxConcurrentDownloads)
  155. for _ in 0 ..< initialConcurrentDownloads {
  156. if let resource = self.pendingResources.popFirst() {
  157. self.startPrefetching(resource)
  158. }
  159. }
  160. }
  161. /// Stops current downloading progress, and cancel any future prefetching activity that might be occuring.
  162. public func stop() {
  163. if finished { return }
  164. stopped = true
  165. tasks.values.forEach { $0.cancel() }
  166. }
  167. func downloadAndCache(_ resource: Resource) {
  168. let downloadTaskCompletionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void) = { result in
  169. self.tasks.removeValue(forKey: resource.downloadURL)
  170. do {
  171. let _ = try result.get()
  172. self.completedResources.append(resource)
  173. } catch {
  174. self.failedResources.append(resource)
  175. }
  176. self.reportProgress()
  177. if self.stopped {
  178. if self.tasks.isEmpty {
  179. self.failedResources.append(contentsOf: self.pendingResources)
  180. self.handleComplete()
  181. }
  182. } else {
  183. self.reportCompletionOrStartNext()
  184. }
  185. }
  186. let downloadTask = manager.loadAndCacheImage(
  187. source: .network(resource),
  188. options: optionsInfo,
  189. completionHandler: downloadTaskCompletionHandler)
  190. if let downloadTask = downloadTask {
  191. tasks[resource.downloadURL] = downloadTask
  192. }
  193. }
  194. func append(cached resource: Resource) {
  195. skippedResources.append(resource)
  196. reportProgress()
  197. reportCompletionOrStartNext()
  198. }
  199. func startPrefetching(_ resource: Resource)
  200. {
  201. if optionsInfo.forceRefresh {
  202. downloadAndCache(resource)
  203. return
  204. }
  205. let cacheType = manager.cache.imageCachedType(
  206. forKey: resource.cacheKey,
  207. processorIdentifier: optionsInfo.processor.identifier)
  208. switch cacheType {
  209. case .memory:
  210. append(cached: resource)
  211. case .disk:
  212. if optionsInfo.alsoPrefetchToMemory {
  213. _ = manager.retrieveImageFromCache(
  214. source: .network(resource),
  215. options: optionsInfo)
  216. {
  217. _ in
  218. self.append(cached: resource)
  219. }
  220. } else {
  221. append(cached: resource)
  222. }
  223. case .none:
  224. downloadAndCache(resource)
  225. }
  226. }
  227. func reportProgress() {
  228. progressBlock?(skippedResources, failedResources, completedResources)
  229. }
  230. func reportCompletionOrStartNext() {
  231. if let resource = self.pendingResources.popFirst() {
  232. startPrefetching(resource)
  233. } else {
  234. guard tasks.isEmpty else { return }
  235. handleComplete()
  236. }
  237. }
  238. func handleComplete() {
  239. // The completion handler should be called on the main thread
  240. DispatchQueue.main.safeAsync {
  241. self.completionHandler?(self.skippedResources, self.failedResources, self.completedResources)
  242. self.completionHandler = nil
  243. self.progressBlock = nil
  244. }
  245. }
  246. }