ImagePrefetcher.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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) 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(OSX)
  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]) -> ())
  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]) -> ())
  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. private let prefetchResources: [Resource]
  49. private let optionsInfo: KingfisherOptionsInfo
  50. private var progressBlock: PrefetcherProgressBlock?
  51. private var completionHandler: PrefetcherCompletionHandler?
  52. private var tasks = [NSURL: RetrieveImageDownloadTask]()
  53. private var skippedResources = [Resource]()
  54. private var completedResources = [Resource]()
  55. private var failedResources = [Resource]()
  56. private var requestedCount = 0
  57. private var stopped = false
  58. // The created manager used for prefetch. We will use the helper method in manager.
  59. private let manager: KingfisherManager
  60. private var finished: Bool {
  61. return failedResources.count + skippedResources.count + completedResources.count == prefetchResources.count
  62. }
  63. /**
  64. Init an image prefetcher with an array of URLs.
  65. The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable.
  66. After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
  67. The images already cached will be skipped without downloading again.
  68. - parameter urls: The URLs which should be prefetched.
  69. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  70. - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled.
  71. - parameter completionHandler: Called when the whole prefetching process finished.
  72. - returns: An `ImagePrefetcher` object.
  73. - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
  74. the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`.
  75. Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
  76. */
  77. public convenience init(urls: [NSURL],
  78. optionsInfo: KingfisherOptionsInfo? = nil,
  79. progressBlock: PrefetcherProgressBlock? = nil,
  80. completionHandler: PrefetcherCompletionHandler? = nil)
  81. {
  82. let resources = urls.map { Resource(downloadURL: $0) }
  83. self.init(resources: resources, optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler)
  84. }
  85. /**
  86. Init an image prefetcher with an array of resources.
  87. The prefetcher should be initiated with a list of prefetching targets. The resources list is immutable.
  88. After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
  89. The images already cached will be skipped without downloading again.
  90. - parameter resources: The resources which should be prefetched. See `Resource` type for more.
  91. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  92. - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled.
  93. - parameter completionHandler: Called when the whole prefetching process finished.
  94. - returns: An `ImagePrefetcher` object.
  95. - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
  96. the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`.
  97. Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
  98. */
  99. public init(resources: [Resource],
  100. optionsInfo: KingfisherOptionsInfo? = nil,
  101. progressBlock: PrefetcherProgressBlock? = nil,
  102. completionHandler: PrefetcherCompletionHandler? = nil)
  103. {
  104. prefetchResources = resources
  105. // We want all callbacks from main queue, so we ignore the call back queue in options
  106. let optionsInfoWithoutQueue = optionsInfo?.kf_removeAllMatchesIgnoringAssociatedValue(.CallbackDispatchQueue(nil))
  107. self.optionsInfo = optionsInfoWithoutQueue ?? KingfisherEmptyOptionsInfo
  108. let cache = self.optionsInfo.targetCache ?? ImageCache.defaultCache
  109. let downloader = self.optionsInfo.downloader ?? ImageDownloader.defaultDownloader
  110. manager = KingfisherManager(downloader: downloader, cache: cache)
  111. self.progressBlock = progressBlock
  112. self.completionHandler = completionHandler
  113. }
  114. /**
  115. Start to download the resources and cache them. This can be useful for background downloading
  116. of assets that are required for later use in an app. This code will not try and update any UI
  117. with the results of the process.
  118. */
  119. public func start()
  120. {
  121. // Since we want to handle the resources cancellation in main thread only.
  122. dispatch_async_safely_to_main_queue { () -> () in
  123. guard !self.stopped else {
  124. assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.")
  125. self.handleComplete()
  126. return
  127. }
  128. guard self.maxConcurrentDownloads > 0 else {
  129. assertionFailure("There should be concurrent downloads value should be at least 1.")
  130. self.handleComplete()
  131. return
  132. }
  133. guard self.prefetchResources.count > 0 else {
  134. self.handleComplete()
  135. return
  136. }
  137. let initialConcurentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads)
  138. for i in 0 ..< initialConcurentDownloads {
  139. self.startPrefetchingResource(self.prefetchResources[i])
  140. }
  141. }
  142. }
  143. /**
  144. Stop current downloading progress, and cancel any future prefetching activity that might be occuring.
  145. */
  146. public func stop() {
  147. dispatch_async_safely_to_main_queue {
  148. if self.finished {
  149. return
  150. }
  151. self.stopped = true
  152. self.tasks.forEach { (_, task) -> () in
  153. task.cancel()
  154. }
  155. }
  156. }
  157. func downloadAndCacheResource(resource: Resource) {
  158. let task = RetrieveImageTask()
  159. let downloadTask = manager.downloadAndCacheImageWithURL(
  160. resource.downloadURL,
  161. forKey: resource.cacheKey,
  162. retrieveImageTask: task,
  163. progressBlock: nil,
  164. completionHandler: {
  165. (image, error, _, _) -> () in
  166. self.tasks.removeValueForKey(resource.downloadURL)
  167. if let _ = error {
  168. self.failedResources.append(resource)
  169. } else {
  170. self.completedResources.append(resource)
  171. }
  172. self.reportProgress()
  173. if self.stopped {
  174. if self.tasks.isEmpty {
  175. let pendingResources = self.prefetchResources[self.requestedCount..<self.prefetchResources.count]
  176. self.failedResources += Array(pendingResources)
  177. self.handleComplete()
  178. }
  179. } else {
  180. self.reportCompletionOrStartNext()
  181. }
  182. },
  183. options: optionsInfo)
  184. if let downloadTask = downloadTask {
  185. tasks[resource.downloadURL] = downloadTask
  186. }
  187. }
  188. func appendCachedResource(resource: Resource) {
  189. skippedResources.append(resource)
  190. reportProgress()
  191. reportCompletionOrStartNext()
  192. }
  193. func startPrefetchingResource(resource: Resource)
  194. {
  195. requestedCount += 1
  196. if optionsInfo.forceRefresh {
  197. downloadAndCacheResource(resource)
  198. } else {
  199. let alreadyInCache = manager.cache.isImageCachedForKey(resource.cacheKey).cached
  200. if alreadyInCache {
  201. appendCachedResource(resource)
  202. } else {
  203. downloadAndCacheResource(resource)
  204. }
  205. }
  206. }
  207. func reportProgress() {
  208. progressBlock?(skippedResources: skippedResources, failedResources: failedResources, completedResources: completedResources)
  209. }
  210. func reportCompletionOrStartNext() {
  211. if finished {
  212. handleComplete()
  213. } else {
  214. if requestedCount < prefetchResources.count {
  215. startPrefetchingResource(prefetchResources[requestedCount])
  216. }
  217. }
  218. }
  219. func handleComplete() {
  220. completionHandler?(skippedResources: skippedResources, failedResources: failedResources, completedResources: completedResources)
  221. completionHandler = nil
  222. progressBlock = nil
  223. }
  224. }