KingfisherManager.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 and default downloader.
  77. */
  78. public init() {
  79. cache = ImageCache.defaultCache
  80. downloader = ImageDownloader.defaultDownloader
  81. }
  82. /**
  83. Get an image with resource.
  84. If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
  85. If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`.
  86. These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
  87. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
  88. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  89. - parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
  90. - parameter completionHandler: Called when the whole retrieving process finished.
  91. - returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
  92. */
  93. public func retrieveImageWithResource(resource: Resource,
  94. optionsInfo: KingfisherOptionsInfo?,
  95. progressBlock: DownloadProgressBlock?,
  96. completionHandler: CompletionHandler?) -> RetrieveImageTask
  97. {
  98. let task = RetrieveImageTask()
  99. if let optionsInfo = optionsInfo where optionsInfo.forceRefresh {
  100. downloadAndCacheImageWithURL(resource.downloadURL,
  101. forKey: resource.cacheKey,
  102. retrieveImageTask: task,
  103. progressBlock: progressBlock,
  104. completionHandler: completionHandler,
  105. options: optionsInfo)
  106. } else {
  107. tryToRetrieveImageFromCacheForKey(resource.cacheKey,
  108. withURL: resource.downloadURL,
  109. retrieveImageTask: task,
  110. progressBlock: progressBlock,
  111. completionHandler: completionHandler,
  112. options: optionsInfo)
  113. }
  114. return task
  115. }
  116. /**
  117. Get an image with `URL.absoluteString` as the key.
  118. If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
  119. If not found, it will download the image at URL and cache it with `URL.absoluteString` value as its key.
  120. 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.
  121. These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
  122. - parameter URL: The image URL.
  123. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  124. - parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
  125. - parameter completionHandler: Called when the whole retrieving process finished.
  126. - returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
  127. */
  128. public func retrieveImageWithURL(URL: NSURL,
  129. optionsInfo: KingfisherOptionsInfo?,
  130. progressBlock: DownloadProgressBlock?,
  131. completionHandler: CompletionHandler?) -> RetrieveImageTask
  132. {
  133. return retrieveImageWithResource(Resource(downloadURL: URL), optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler)
  134. }
  135. func downloadAndCacheImageWithURL(URL: NSURL,
  136. forKey key: String,
  137. retrieveImageTask: RetrieveImageTask,
  138. progressBlock: DownloadProgressBlock?,
  139. completionHandler: CompletionHandler?,
  140. options: KingfisherOptionsInfo?)
  141. {
  142. let downloader = options?.downloader ?? self.downloader
  143. downloader.downloadImageWithURL(URL, retrieveImageTask: retrieveImageTask, options: options,
  144. progressBlock: { receivedSize, totalSize in
  145. progressBlock?(receivedSize: receivedSize, totalSize: totalSize)
  146. },
  147. completionHandler: { image, error, imageURL, originalData in
  148. let targetCache = options?.targetCache ?? self.cache
  149. if let error = error where error.code == KingfisherError.NotModified.rawValue {
  150. // Not modified. Try to find the image from cache.
  151. // (The image should be in cache. It should be guaranteed by the framework users.)
  152. targetCache.retrieveImageForKey(key, options: options, completionHandler: { (cacheImage, cacheType) -> () in
  153. completionHandler?(image: cacheImage, error: nil, cacheType: cacheType, imageURL: URL)
  154. })
  155. return
  156. }
  157. if let image = image, originalData = originalData {
  158. targetCache.storeImage(image, originalData: originalData, forKey: key, toDisk: options?.cacheMemoryOnly ?? true, completionHandler: nil)
  159. }
  160. completionHandler?(image: image, error: error, cacheType: .None, imageURL: URL)
  161. })
  162. }
  163. func tryToRetrieveImageFromCacheForKey(key: String,
  164. withURL URL: NSURL,
  165. retrieveImageTask: RetrieveImageTask,
  166. progressBlock: DownloadProgressBlock?,
  167. completionHandler: CompletionHandler?,
  168. options: KingfisherOptionsInfo?)
  169. {
  170. let diskTaskCompletionHandler: CompletionHandler = { (image, error, cacheType, imageURL) -> () in
  171. // Break retain cycle created inside diskTask closure below
  172. retrieveImageTask.diskRetrieveTask = nil
  173. completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
  174. }
  175. let targetCache = options?.targetCache ?? cache
  176. let diskTask = targetCache.retrieveImageForKey(key, options: options,
  177. completionHandler: { image, cacheType in
  178. if image != nil {
  179. diskTaskCompletionHandler(image: image, error: nil, cacheType:cacheType, imageURL: URL)
  180. } else {
  181. self.downloadAndCacheImageWithURL(URL,
  182. forKey: key,
  183. retrieveImageTask: retrieveImageTask,
  184. progressBlock: progressBlock,
  185. completionHandler: diskTaskCompletionHandler,
  186. options: options)
  187. }
  188. })
  189. retrieveImageTask.diskRetrieveTask = diskTask
  190. }
  191. }