ImagePrefetcher.swift 12 KB

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