ImagePrefetcher.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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 = ((completedURLs: Int, skippedURLs: Int) -> ())
  35. /// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs and caching them.
  36. public class ImagePrefetcher: NSObject {
  37. private var prefetchURLs: [NSURL]?
  38. private var skippedCount = 0
  39. private var requestedCount = 0
  40. private var finishedCount = 0
  41. private var downloader: ImageDownloader
  42. /// The maximum concurrent downloads to use when prefetching images. Default is 5.
  43. var maxConcurrentDownloads = 5
  44. public init(downloader: ImageDownloader) {
  45. self.downloader = downloader
  46. super.init()
  47. }
  48. /**
  49. Download the images from `urls` and cache them. This can be useful for background downloading
  50. of assets that are required for later use in an app. This code will not try and update any UI
  51. with the results of the process, but calls the handlers with the number cached etc. Failed
  52. images are just skipped.
  53. - parameter urls: The list of URLs to prefetch
  54. - parameter progressBlock: Block to be called when progress updates. Completed and total
  55. counts are provided. Completed does not imply success.
  56. - parameter completionHandler: Block to be called when prefetching is complete. Completed is all
  57. those made, and skipped is the number of failed ones.
  58. */
  59. public func prefetchURLs(urls: [NSURL], progressBlock: PrefetchProgressBlock?, completionHandler: PrefetchCompletionBlock?) {
  60. // Clear out any existing prefetch operation first
  61. cancelPrefetching()
  62. prefetchURLs = urls
  63. guard urls.count > 0 else {
  64. CompletionHandler?()
  65. return
  66. }
  67. for (var i = 0; i < maxConcurrentDownloads && requestedCount < urls.count; i++) {
  68. startPrefetching(i, progressBlock: progressBlock, completionHandler: completionHandler)
  69. }
  70. }
  71. internal func cancelPrefetching() {
  72. prefetchURLs = .None
  73. skippedCount = 0
  74. requestedCount = 0
  75. finishedCount = 0
  76. }
  77. internal func startPrefetching(index: Int, progressBlock: PrefetchProgressBlock?, completionHandler: PrefetchCompletionBlock?) {
  78. guard let urls = prefetchURLs where index < (urls.count ?? 0) else { return }
  79. requestedCount++
  80. let task = RetrieveImageTask()
  81. let resource = Resource(downloadURL: urls[index])
  82. KingfisherManager.sharedManager.downloadAndCacheImageWithURL(resource.downloadURL, forKey: resource.cacheKey, retrieveImageTask: task, progressBlock: nil, completionHandler: { image, error, cacheType, imageURL in
  83. self.finishedCount++
  84. if image == .None {
  85. self.skippedCount++
  86. }
  87. progressBlock?(completedURLs: self.finishedCount, allURLs: urls.count)
  88. if urls.count > self.requestedCount {
  89. self.startPrefetching(self.requestedCount, progressBlock: progressBlock, completionHandler: completionHandler)
  90. } else if self.finishedCount == self.requestedCount {
  91. completionHandler?(completedURLs: self.finishedCount, skippedURLs: self.skippedCount)
  92. }
  93. }, options: nil)
  94. }
  95. }