ImagePrefetcher.swift 12 KB

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