KingfisherManager.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. //
  2. // KingfisherManager.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  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. public typealias DownloadProgressBlock = ((receivedSize: Int64, totalSize: Int64) -> ())
  32. public typealias CompletionHandler = ((image: Image?, error: NSError?, cacheType: CacheType, imageURL: NSURL?) -> ())
  33. /// RetrieveImageTask represents a task of image retrieving process.
  34. /// It contains an async task of getting image from disk and from network.
  35. public class RetrieveImageTask {
  36. // If task is canceled before the download task started (which means the `downloadTask` is nil),
  37. // the download task should not begin.
  38. var cancelledBeforeDownlodStarting: Bool = false
  39. /// The disk retrieve task in this image task. Kingfisher will try to look up in cache first. This task represent the cache search task.
  40. public var diskRetrieveTask: RetrieveImageDiskTask?
  41. /// The network retrieve task in this image task.
  42. public var downloadTask: RetrieveImageDownloadTask?
  43. /**
  44. Cancel current task. If this task does not begin or already done, do nothing.
  45. */
  46. public func cancel() {
  47. // From Xcode 7 beta 6, the `dispatch_block_cancel` will crash at runtime.
  48. // It fixed in Xcode 7.1.
  49. // See https://github.com/onevcat/Kingfisher/issues/99 for more.
  50. if let diskRetrieveTask = diskRetrieveTask {
  51. dispatch_block_cancel(diskRetrieveTask)
  52. }
  53. if let downloadTask = downloadTask {
  54. downloadTask.cancel()
  55. } else {
  56. cancelledBeforeDownlodStarting = true
  57. }
  58. }
  59. }
  60. /// Error domain of Kingfisher
  61. public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error"
  62. private let instance = KingfisherManager()
  63. /// Main manager class of Kingfisher. It connects Kingfisher downloader and cache.
  64. /// You can use this class to retrieve an image via a specified URL from web or cache.
  65. public class KingfisherManager {
  66. /// Shared manager used by the extensions across Kingfisher.
  67. public class var sharedManager: KingfisherManager {
  68. return instance
  69. }
  70. /// Cache used by this manager
  71. public var cache: ImageCache
  72. /// Downloader used by this manager
  73. public var downloader: ImageDownloader
  74. /**
  75. Default init method
  76. - returns: A Kingfisher manager object with default cache, default downloader, and default prefetcher.
  77. */
  78. public convenience init() {
  79. self.init(downloader: ImageDownloader.defaultDownloader, cache: ImageCache.defaultCache)
  80. }
  81. init(downloader: ImageDownloader, cache: ImageCache) {
  82. self.downloader = downloader
  83. self.cache = cache
  84. }
  85. /**
  86. Get an image with resource.
  87. If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
  88. If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`.
  89. These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
  90. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
  91. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  92. - parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
  93. - parameter completionHandler: Called when the whole retrieving process finished.
  94. - returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
  95. */
  96. public func retrieveImageWithResource(resource: Resource,
  97. optionsInfo: KingfisherOptionsInfo?,
  98. progressBlock: DownloadProgressBlock?,
  99. completionHandler: CompletionHandler?) -> RetrieveImageTask
  100. {
  101. let task = RetrieveImageTask()
  102. if let optionsInfo = optionsInfo where optionsInfo.forceRefresh {
  103. downloadAndCacheImageWithURL(resource.downloadURL,
  104. forKey: resource.cacheKey,
  105. retrieveImageTask: task,
  106. progressBlock: progressBlock,
  107. completionHandler: completionHandler,
  108. options: optionsInfo)
  109. } else {
  110. tryToRetrieveImageFromCacheForKey(resource.cacheKey,
  111. withURL: resource.downloadURL,
  112. retrieveImageTask: task,
  113. progressBlock: progressBlock,
  114. completionHandler: completionHandler,
  115. options: optionsInfo)
  116. }
  117. return task
  118. }
  119. /**
  120. Get an image with `URL.absoluteString` as the key.
  121. If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
  122. If not found, it will download the image at URL and cache it with `URL.absoluteString` value as its key.
  123. If you need to specify the key other than `URL.absoluteString`, please use resource version of this API with `resource.cacheKey` set to what you want.
  124. These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
  125. - parameter URL: The image URL.
  126. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  127. - parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
  128. - parameter completionHandler: Called when the whole retrieving process finished.
  129. - returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
  130. */
  131. public func retrieveImageWithURL(URL: NSURL,
  132. optionsInfo: KingfisherOptionsInfo?,
  133. progressBlock: DownloadProgressBlock?,
  134. completionHandler: CompletionHandler?) -> RetrieveImageTask
  135. {
  136. return retrieveImageWithResource(Resource(downloadURL: URL), optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler)
  137. }
  138. func downloadAndCacheImageWithURL(URL: NSURL,
  139. forKey key: String,
  140. retrieveImageTask: RetrieveImageTask,
  141. progressBlock: DownloadProgressBlock?,
  142. completionHandler: CompletionHandler?,
  143. options: KingfisherOptionsInfo?) -> RetrieveImageDownloadTask?
  144. {
  145. let downloader = options?.downloader ?? self.downloader
  146. return downloader.downloadImageWithURL(URL, retrieveImageTask: retrieveImageTask, options: options,
  147. progressBlock: { receivedSize, totalSize in
  148. progressBlock?(receivedSize: receivedSize, totalSize: totalSize)
  149. },
  150. completionHandler: { image, error, imageURL, originalData in
  151. let targetCache = options?.targetCache ?? self.cache
  152. if let error = error where error.code == KingfisherError.NotModified.rawValue {
  153. // Not modified. Try to find the image from cache.
  154. // (The image should be in cache. It should be guaranteed by the framework users.)
  155. targetCache.retrieveImageForKey(key, options: options, completionHandler: { (cacheImage, cacheType) -> () in
  156. completionHandler?(image: cacheImage, error: nil, cacheType: cacheType, imageURL: URL)
  157. })
  158. return
  159. }
  160. if let image = image, originalData = originalData {
  161. targetCache.storeImage(image, originalData: originalData, forKey: key, toDisk: !(options?.cacheMemoryOnly ?? false), completionHandler: nil)
  162. }
  163. completionHandler?(image: image, error: error, cacheType: .None, imageURL: URL)
  164. })
  165. }
  166. func tryToRetrieveImageFromCacheForKey(key: String,
  167. withURL URL: NSURL,
  168. retrieveImageTask: RetrieveImageTask,
  169. progressBlock: DownloadProgressBlock?,
  170. completionHandler: CompletionHandler?,
  171. options: KingfisherOptionsInfo?)
  172. {
  173. let diskTaskCompletionHandler: CompletionHandler = { (image, error, cacheType, imageURL) -> () in
  174. // Break retain cycle created inside diskTask closure below
  175. retrieveImageTask.diskRetrieveTask = nil
  176. completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
  177. }
  178. let targetCache = options?.targetCache ?? cache
  179. let diskTask = targetCache.retrieveImageForKey(key, options: options,
  180. completionHandler: { image, cacheType in
  181. if image != nil {
  182. diskTaskCompletionHandler(image: image, error: nil, cacheType:cacheType, imageURL: URL)
  183. } else {
  184. self.downloadAndCacheImageWithURL(URL,
  185. forKey: key,
  186. retrieveImageTask: retrieveImageTask,
  187. progressBlock: progressBlock,
  188. completionHandler: diskTaskCompletionHandler,
  189. options: options)
  190. }
  191. })
  192. retrieveImageTask.diskRetrieveTask = diskTask
  193. }
  194. }