ImagePrefetcher.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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. public typealias PrefetchProgressBlock = ((completedURLs: Int, allURLs: Int) -> ())
  33. /// Completion block of prefetcher.
  34. public typealias PrefetchCompletionBlock = ((cancelled: Bool, completedURLs: Int, skippedURLs: Int) -> ())
  35. private let defaultPrefetcherInstance = ImagePrefetcher()
  36. /// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs and caching them.
  37. public class ImagePrefetcher: NSObject {
  38. private var prefetchURLs: [NSURL]?
  39. private var skippedCount = 0
  40. private var requestedCount = 0
  41. private var finishedCount = 0
  42. private var cancelCompletionHandlerCalled = false
  43. /// The default manager to use for downloads.
  44. public lazy var manager: KingfisherManager = KingfisherManager.sharedManager
  45. /// The default prefetcher.
  46. public class var defaultPrefetcher: ImagePrefetcher {
  47. return defaultPrefetcherInstance
  48. }
  49. /// The maximum concurrent downloads to use when prefetching images. Default is 5.
  50. public var maxConcurrentDownloads = 5
  51. /**
  52. Download the images from `urls` and cache them. This can be useful for background downloading
  53. of assets that are required for later use in an app. This code will not try and update any UI
  54. with the results of the process, but calls the handlers with the number cached etc. Failed
  55. images are just skipped.
  56. Warning: This will cancel any existing prefetch operation in progress! Use `isPrefetching() to
  57. control this in your own code as you see fit.
  58. - parameter urls: The list of URLs to prefetch
  59. - parameter progressBlock: Block to be called when progress updates. Completed and total
  60. counts are provided. Completed does not imply success.
  61. - parameter completionHandler: Block to be called when prefetching is complete. Completed is all
  62. those made, and skipped is the number of failed ones.
  63. */
  64. public func prefetchURLs(urls: [NSURL], progressBlock: PrefetchProgressBlock?, completionHandler: PrefetchCompletionBlock?) {
  65. // Clear out any existing prefetch operation first
  66. cancelPrefetching()
  67. cancelCompletionHandlerCalled = false
  68. prefetchURLs = urls
  69. guard urls.count > 0 else {
  70. CompletionHandler?()
  71. return
  72. }
  73. for i in (0..<urls.count) where i < maxConcurrentDownloads && requestedCount < urls.count {
  74. startPrefetching(i, progressBlock: progressBlock, completionHandler: completionHandler)
  75. }
  76. }
  77. /**
  78. This cancels any existing prefetching activity that might be occuring. It does not stop any currently
  79. running cache operation, but prevents any further ones being started and terminates the looping. For
  80. surety, be sure that the completion block on the prefetch is called after calling this if you expect
  81. an operation to be running.
  82. */
  83. func cancelPrefetching() {
  84. prefetchURLs = .None
  85. skippedCount = 0
  86. requestedCount = 0
  87. finishedCount = 0
  88. }
  89. /**
  90. Checks to see if this prefetcher is already prefetching any images.
  91. - returns: True if there are images still to be prefetched, false otherwise.
  92. */
  93. func isPrefetching() -> Bool {
  94. guard let urls = prefetchURLs else { return false }
  95. return urls.count > 0
  96. }
  97. internal func startPrefetching(index: Int, progressBlock: PrefetchProgressBlock?, completionHandler: PrefetchCompletionBlock?) {
  98. guard let urls = prefetchURLs where index < (urls.count ?? 0) else { return }
  99. requestedCount++
  100. let task = RetrieveImageTask()
  101. let resource = Resource(downloadURL: urls[index])
  102. let total = urls.count
  103. manager.downloadAndCacheImageWithURL(resource.downloadURL, forKey: resource.cacheKey, retrieveImageTask: task, progressBlock: nil, completionHandler: { image, error, cacheType, imageURL in
  104. self.finishedCount++
  105. if image == .None {
  106. self.skippedCount++
  107. }
  108. progressBlock?(completedURLs: self.finishedCount, allURLs: total)
  109. // Reference the prefetchURLs rather than urls in case the request has been cancelled
  110. if (self.prefetchURLs?.count ?? 0) > self.requestedCount {
  111. self.startPrefetching(self.requestedCount, progressBlock: progressBlock, completionHandler: completionHandler)
  112. } else if self.finishedCount == self.requestedCount {
  113. self.prefetchURLs?.removeAll()
  114. completionHandler?(cancelled: false, completedURLs: self.finishedCount, skippedURLs: self.skippedCount)
  115. } else if (self.prefetchURLs == nil || self.prefetchURLs!.count == 0) && !self.cancelCompletionHandlerCalled {
  116. self.cancelCompletionHandlerCalled = true
  117. completionHandler?(cancelled: true, completedURLs: self.finishedCount, skippedURLs: self.skippedCount)
  118. }
  119. }, options: nil)
  120. }
  121. }