ImageDownloader.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. //
  2. // ImageDownloader.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  6. //
  7. // Copyright (c) 2018 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(macOS)
  27. import AppKit
  28. #else
  29. import UIKit
  30. #endif
  31. /// Represents a success result of an image downloading progess.
  32. public struct ImageDownloadResult {
  33. /// The downloaded image.
  34. public let image: Image
  35. /// Original URL of the image request.
  36. public let url: URL
  37. /// The raw data received from downloader.
  38. public let originalData: Data
  39. }
  40. /// Represents a task of an image downloading process.
  41. public struct DownloadTask {
  42. /// The `SessionDataTask` object bounded to this download task. Multiple `DownloadTask`s could refer
  43. /// to a same `sessionTask`. This is an optimization in Kingfisher to prevent multiple downloading task
  44. /// for the same URL resource at the same time.
  45. ///
  46. /// When you `cancel` a `DownloadTask`, this `SessionDataTask` and its cancel token will be pass through.
  47. /// You can use them to identify the cancelled task.
  48. public let sessionTask: SessionDataTask
  49. /// The cancel token which is used to cancel the task. This is only for identify the task when it is cancelled.
  50. /// To cancel a `DownloadTask`, use `cancel` instead.
  51. public let cancelToken: SessionDataTask.CancelToken
  52. /// Cancel this task if it is running. It will do nothing if this task is not running.
  53. ///
  54. /// - Note:
  55. /// In Kingfisher, there is an optimization to prevent starting another download task if the target URL is being
  56. /// downloading. However, even when internally no new session task created, a `DownloadTask` will be still created
  57. /// and returned when you call related methods, but it will share the session downloading task with a previous task.
  58. /// In this case, if multiple `DownloadTask`s share a single session download task, cancelling a `DownloadTask`
  59. /// does not affect other `DownloadTask`s.
  60. ///
  61. /// If you need to cancel all `DownloadTask`s of a url, use `ImageDownloader.cancel(url:)`. If you need to cancel
  62. /// all downloading tasks of an `ImageDownloader`, use `ImageDownloader.cancelAll()`.
  63. public func cancel() {
  64. sessionTask.cancel(token: cancelToken)
  65. }
  66. }
  67. /// Represents a downloading manager for requesting the image with a URL from server.
  68. open class ImageDownloader {
  69. /// The default downloader.
  70. public static let `default` = ImageDownloader(name: "default")
  71. // MARK: - Public property
  72. /// The duration before the downloading is timeout. Default is 15 seconds.
  73. open var downloadTimeout: TimeInterval = 15.0
  74. /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this
  75. /// set will be ignored. You can use this set to specify the self-signed site. It only will be used if you don't
  76. /// specify the `authenticationChallengeResponder`.
  77. ///
  78. /// If `authenticationChallengeResponder` is set, this property will be ignored and the implementation of
  79. /// `authenticationChallengeResponder` will be used instead.
  80. open var trustedHosts: Set<String>?
  81. /// Use this to set supply a configuration for the downloader. By default,
  82. /// NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used.
  83. ///
  84. /// You could change the configuration before a downloading task starts.
  85. /// A configuration without persistent storage for caches is requested for downloader working correctly.
  86. open var sessionConfiguration = URLSessionConfiguration.ephemeral {
  87. didSet {
  88. session.invalidateAndCancel()
  89. session = URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil)
  90. }
  91. }
  92. /// Whether the download requests should use pipline or not. Default is false.
  93. open var requestsUsePipelining = false
  94. /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more.
  95. open weak var delegate: ImageDownloaderDelegate?
  96. /// A responder for authentication challenge.
  97. /// Downloader will forward the received authentication challenge for the downloading session to this responder.
  98. open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable?
  99. private let name: String
  100. private let sessionDelegate: SessionDelegate
  101. private var session: URLSession
  102. /// Creates a downloader with name.
  103. ///
  104. /// - Parameter name: The name for the downloader. It should not be empty.
  105. public init(name: String) {
  106. if name.isEmpty {
  107. fatalError("[Kingfisher] You should specify a name for the downloader. "
  108. + "A downloader with empty name is not permitted.")
  109. }
  110. self.name = name
  111. sessionDelegate = SessionDelegate()
  112. session = URLSession(
  113. configuration: sessionConfiguration,
  114. delegate: sessionDelegate,
  115. delegateQueue: nil)
  116. authenticationChallengeResponder = self
  117. setupSessionHandler()
  118. }
  119. deinit { session.invalidateAndCancel() }
  120. private func setupSessionHandler() {
  121. sessionDelegate.onReceiveSessionChallenge.delegate(on: self) { (self, invoke) in
  122. self.authenticationChallengeResponder?.downloader(self, didReceive: invoke.1, completionHandler: invoke.2)
  123. }
  124. sessionDelegate.onReceiveSessionTaskChallenge.delegate(on: self) { (self, invoke) in
  125. self.authenticationChallengeResponder?.downloader(
  126. self, task: invoke.1, didReceive: invoke.2, completionHandler: invoke.3)
  127. }
  128. sessionDelegate.onValidStatusCode.delegate(on: self) { (self, code) in
  129. return (self.delegate ?? self).isValidStatusCode(code, for: self)
  130. }
  131. sessionDelegate.onDownloadingFinished.delegate(on: self) { (self, value) in
  132. let (url, result) = value
  133. self.delegate?.imageDownloader(
  134. self, didFinishDownloadingImageForURL: url, with: result.value, error: result.error)
  135. }
  136. sessionDelegate.onDidDownloadData.delegate(on: self) { (self, task) in
  137. guard let url = task.task.originalRequest?.url else {
  138. return task.mutableData
  139. }
  140. return (self.delegate ?? self).imageDownloader(self, didDownload: task.mutableData, for: url)
  141. }
  142. }
  143. /// Downloads an image with a URL and option.
  144. ///
  145. /// - Parameters:
  146. /// - url: Target URL.
  147. /// - options: The options could control download behavior. See `KingfisherOptionsInfo`.
  148. /// - progressBlock: Called when the download progress updated. This block will be always be called in main queue.
  149. /// - completionHandler: Called when the download progress finishes. This block will be called in the queue
  150. /// defined in `.callbackQueue` in `options` parameter.
  151. /// - Returns: A downloading task. You could call `cancel` on it to stop the download task.
  152. @discardableResult
  153. open func downloadImage(with url: URL,
  154. options: KingfisherOptionsInfo? = nil,
  155. progressBlock: DownloadProgressBlock? = nil,
  156. completionHandler: ((Result<ImageDownloadResult, KingfisherError>) -> Void)? = nil)
  157. -> DownloadTask?
  158. {
  159. // Creates default request.
  160. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: downloadTimeout)
  161. request.httpShouldUsePipelining = requestsUsePipelining
  162. let options = options ?? .empty
  163. // Modifies request before sending.
  164. guard let r = options.modifier.modified(for: request) else {
  165. options.callbackQueue.execute {
  166. completionHandler?(.failure(KingfisherError.requestError(reason: .emptyRequest)))
  167. }
  168. return nil
  169. }
  170. request = r
  171. // There is a possibility that request modifier changed the url to `nil` or empty.
  172. // In this case, throw an error.
  173. guard let url = request.url, !url.absoluteString.isEmpty else {
  174. options.callbackQueue.execute {
  175. completionHandler?(.failure(KingfisherError.requestError(reason: .invalidURL(request: request))))
  176. }
  177. return nil
  178. }
  179. // Wraps `progressBlock` and `completionHandler` to `onProgress` and `onCompleted` respectively.
  180. let onProgress = progressBlock.map {
  181. block -> Delegate<(Int64, Int64), Void> in
  182. let delegate = Delegate<(Int64, Int64), Void>()
  183. delegate.delegate(on: self) { (_, progress) in
  184. let (downloaded, total) = progress
  185. block(downloaded, total)
  186. }
  187. return delegate
  188. }
  189. let onCompleted = completionHandler.map {
  190. block -> Delegate<Result<ImageDownloadResult, KingfisherError>, Void> in
  191. let delegate = Delegate<Result<ImageDownloadResult, KingfisherError>, Void>()
  192. delegate.delegate(on: self) { (_, result) in
  193. block(result)
  194. }
  195. return delegate
  196. }
  197. // SessionDataTask.TaskCallback is a wrapper for `onProgress`, `onCompleted` and `options` (for processor info)
  198. let callback = SessionDataTask.TaskCallback(
  199. onProgress: onProgress, onCompleted: onCompleted, options: options)
  200. // Ready to start download. Add it to session task manager (`sessionHandler`)
  201. let dataTask = session.dataTask(with: request)
  202. dataTask.priority = options.downloadPriority
  203. let downloadTask = sessionDelegate.add(dataTask, url: url, callback: callback)
  204. let sessionTask = downloadTask.sessionTask
  205. sessionTask.onTaskDone.delegate(on: self) { (self, done) in
  206. // Underlying downloading finishes.
  207. // result: Result<(Data, URLResponse?)>, callbacks: [TaskCallback]
  208. let (result, callbacks) = done
  209. // Before processing the downloaded data.
  210. self.delegate?.imageDownloader(
  211. self,
  212. didFinishDownloadingImageForURL: url,
  213. with: result.value?.1,
  214. error: result.error)
  215. switch result {
  216. // Download finished. Now process the data to an image.
  217. case .success(let (data, response)):
  218. let prosessor = ImageDataProcessor(name: self.name, data: data, callbacks: callbacks)
  219. prosessor.onImageProcessed.delegate(on: self) { (self, result) in
  220. // `onImageProcessed` will be called for `callbacks.count` times, with each
  221. // `SessionDataTask.TaskCallback` as the input parameter.
  222. // result: Result<Image>, callback: SessionDataTask.TaskCallback
  223. let (result, callback) = result
  224. if let image = result.value {
  225. self.delegate?.imageDownloader(self, didDownload: image, for: url, with: response)
  226. }
  227. let imageResult = result.map { ImageDownloadResult(image: $0, url: url, originalData: data) }
  228. let queue = callback.options.callbackQueue
  229. queue.execute { callback.onCompleted?.call(imageResult) }
  230. }
  231. prosessor.process()
  232. case .failure(let error):
  233. callbacks.forEach { callback in
  234. let queue = callback.options.callbackQueue
  235. queue.execute { callback.onCompleted?.call(.failure(error)) }
  236. }
  237. }
  238. }
  239. // Start the session task if not started yet.
  240. if !sessionTask.started {
  241. delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request)
  242. sessionTask.resume()
  243. }
  244. return downloadTask
  245. }
  246. }
  247. // MARK: - Download method
  248. extension ImageDownloader {
  249. /// Cancel all downloading tasks for this `ImageDownloader`. It will trigger the completion handlers
  250. /// for all not-yet-finished downloading tasks.
  251. ///
  252. /// If you need to only cancel a certain task, call `cancel()` on the `DownloadTask`
  253. /// returned by the downloading methods. If you need to cancel all `DownloadTask`s of a certain url,
  254. /// use `ImageDownloader.cancel(url:)`.
  255. public func cancelAll() {
  256. sessionDelegate.cancelAll()
  257. }
  258. /// Cancel all downloading tasks for a given URL. It will trigger the completion handlers for
  259. /// all not-yet-finished downloading tasks for the URL.
  260. ///
  261. /// - Parameter url: The URL which you want to cancel downloading.
  262. public func cancel(url: URL) {
  263. sessionDelegate.cancel(url: url)
  264. }
  265. }
  266. // Use the default implementation from extension of `AuthenticationChallengeResponsable`.
  267. extension ImageDownloader: AuthenticationChallengeResponsable {}
  268. // Use the default implementation from extension of `ImageDownloaderDelegate`.
  269. extension ImageDownloader: ImageDownloaderDelegate {}