ImageDownloader.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. //
  2. // ImageDownloader.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  6. //
  7. // Copyright (c) 2019 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. typealias DownloadResult = Result<ImageLoadingResult, KingfisherError>
  32. /// Represents a success result of an image downloading progress.
  33. public struct ImageLoadingResult {
  34. /// The downloaded image.
  35. public let image: KFCrossPlatformImage
  36. /// Original URL of the image request.
  37. public let url: URL?
  38. /// The raw data received from downloader.
  39. public let originalData: Data
  40. }
  41. /// Represents a task of an image downloading process.
  42. public struct DownloadTask {
  43. /// The `SessionDataTask` object bounded to this download task. Multiple `DownloadTask`s could refer
  44. /// to a same `sessionTask`. This is an optimization in Kingfisher to prevent multiple downloading task
  45. /// for the same URL resource at the same time.
  46. ///
  47. /// When you `cancel` a `DownloadTask`, this `SessionDataTask` and its cancel token will be pass through.
  48. /// You can use them to identify the cancelled task.
  49. public let sessionTask: SessionDataTask
  50. /// The cancel token which is used to cancel the task. This is only for identify the task when it is cancelled.
  51. /// To cancel a `DownloadTask`, use `cancel` instead.
  52. public let cancelToken: SessionDataTask.CancelToken
  53. /// Cancel this task if it is running. It will do nothing if this task is not running.
  54. ///
  55. /// - Note:
  56. /// In Kingfisher, there is an optimization to prevent starting another download task if the target URL is being
  57. /// downloading. However, even when internally no new session task created, a `DownloadTask` will be still created
  58. /// and returned when you call related methods, but it will share the session downloading task with a previous task.
  59. /// In this case, if multiple `DownloadTask`s share a single session download task, cancelling a `DownloadTask`
  60. /// does not affect other `DownloadTask`s.
  61. ///
  62. /// If you need to cancel all `DownloadTask`s of a url, use `ImageDownloader.cancel(url:)`. If you need to cancel
  63. /// all downloading tasks of an `ImageDownloader`, use `ImageDownloader.cancelAll()`.
  64. public func cancel() {
  65. sessionTask.cancel(token: cancelToken)
  66. }
  67. }
  68. extension DownloadTask {
  69. enum WrappedTask {
  70. case download(DownloadTask)
  71. case dataProviding
  72. func cancel() {
  73. switch self {
  74. case .download(let task): task.cancel()
  75. case .dataProviding: break
  76. }
  77. }
  78. var value: DownloadTask? {
  79. switch self {
  80. case .download(let task): return task
  81. case .dataProviding: return nil
  82. }
  83. }
  84. }
  85. }
  86. /// Represents a downloading manager for requesting the image with a URL from server.
  87. open class ImageDownloader {
  88. // MARK: Singleton
  89. /// The default downloader.
  90. public static let `default` = ImageDownloader(name: "default")
  91. // MARK: Public Properties
  92. /// The duration before the downloading is timeout. Default is 15 seconds.
  93. open var downloadTimeout: TimeInterval = 15.0
  94. /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this
  95. /// set will be ignored. You can use this set to specify the self-signed site. It only will be used if you don't
  96. /// specify the `authenticationChallengeResponder`.
  97. ///
  98. /// If `authenticationChallengeResponder` is set, this property will be ignored and the implementation of
  99. /// `authenticationChallengeResponder` will be used instead.
  100. open var trustedHosts: Set<String>?
  101. /// Use this to set supply a configuration for the downloader. By default,
  102. /// NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used.
  103. ///
  104. /// You could change the configuration before a downloading task starts.
  105. /// A configuration without persistent storage for caches is requested for downloader working correctly.
  106. open var sessionConfiguration = URLSessionConfiguration.ephemeral {
  107. didSet {
  108. session.invalidateAndCancel()
  109. session = URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil)
  110. }
  111. }
  112. open var sessionDelegate: SessionDelegate {
  113. didSet {
  114. session.invalidateAndCancel()
  115. session = URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil)
  116. setupSessionHandler()
  117. }
  118. }
  119. /// Whether the download requests should use pipeline or not. Default is false.
  120. open var requestsUsePipelining = false
  121. /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more.
  122. open weak var delegate: ImageDownloaderDelegate?
  123. /// A responder for authentication challenge.
  124. /// Downloader will forward the received authentication challenge for the downloading session to this responder.
  125. open weak var authenticationChallengeResponder: AuthenticationChallengeResponsible?
  126. private let name: String
  127. private var session: URLSession
  128. // MARK: Initializers
  129. /// Creates a downloader with name.
  130. ///
  131. /// - Parameter name: The name for the downloader. It should not be empty.
  132. public init(name: String) {
  133. if name.isEmpty {
  134. fatalError("[Kingfisher] You should specify a name for the downloader. "
  135. + "A downloader with empty name is not permitted.")
  136. }
  137. self.name = name
  138. sessionDelegate = SessionDelegate()
  139. session = URLSession(
  140. configuration: sessionConfiguration,
  141. delegate: sessionDelegate,
  142. delegateQueue: nil)
  143. authenticationChallengeResponder = self
  144. setupSessionHandler()
  145. }
  146. deinit { session.invalidateAndCancel() }
  147. private func setupSessionHandler() {
  148. sessionDelegate.onReceiveSessionChallenge.delegate(on: self) { (self, invoke) in
  149. self.authenticationChallengeResponder?.downloader(self, didReceive: invoke.1, completionHandler: invoke.2)
  150. }
  151. sessionDelegate.onReceiveSessionTaskChallenge.delegate(on: self) { (self, invoke) in
  152. self.authenticationChallengeResponder?.downloader(
  153. self, task: invoke.1, didReceive: invoke.2, completionHandler: invoke.3)
  154. }
  155. sessionDelegate.onValidStatusCode.delegate(on: self) { (self, code) in
  156. return (self.delegate ?? self).isValidStatusCode(code, for: self)
  157. }
  158. sessionDelegate.onResponseReceived.delegate(on: self) { (self, invoke) in
  159. (self.delegate ?? self).imageDownloader(self, didReceive: invoke.0, completionHandler: invoke.1)
  160. }
  161. sessionDelegate.onDownloadingFinished.delegate(on: self) { (self, value) in
  162. let (url, result) = value
  163. do {
  164. let value = try result.get()
  165. self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: value, error: nil)
  166. } catch {
  167. self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: nil, error: error)
  168. }
  169. }
  170. sessionDelegate.onDidDownloadData.delegate(on: self) { (self, task) in
  171. return (self.delegate ?? self).imageDownloader(self, didDownload: task.mutableData, with: task)
  172. }
  173. }
  174. // Wraps `completionHandler` to `onCompleted` respectively.
  175. private func createCompletionCallBack(_ completionHandler: ((DownloadResult) -> Void)?) -> Delegate<DownloadResult, Void>? {
  176. return completionHandler.map { block -> Delegate<DownloadResult, Void> in
  177. let delegate = Delegate<Result<ImageLoadingResult, KingfisherError>, Void>()
  178. delegate.delegate(on: self) { (self, callback) in
  179. block(callback)
  180. }
  181. return delegate
  182. }
  183. }
  184. private func createTaskCallback(
  185. _ completionHandler: ((DownloadResult) -> Void)?,
  186. options: KingfisherParsedOptionsInfo
  187. ) -> SessionDataTask.TaskCallback
  188. {
  189. return SessionDataTask.TaskCallback(
  190. onCompleted: createCompletionCallBack(completionHandler),
  191. options: options
  192. )
  193. }
  194. private func createDownloadContext(
  195. with url: URL,
  196. options: KingfisherParsedOptionsInfo,
  197. done: @escaping ((Result<DownloadingContext, KingfisherError>) -> Void)
  198. )
  199. {
  200. func checkRequestAndDone(r: URLRequest) {
  201. // There is a possibility that request modifier changed the url to `nil` or empty.
  202. // In this case, throw an error.
  203. guard let url = r.url, !url.absoluteString.isEmpty else {
  204. done(.failure(KingfisherError.requestError(reason: .invalidURL(request: r))))
  205. return
  206. }
  207. done(.success(DownloadingContext(url: url, request: r, options: options)))
  208. }
  209. // Creates default request.
  210. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: downloadTimeout)
  211. request.httpShouldUsePipelining = requestsUsePipelining
  212. if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) , options.lowDataModeSource != nil {
  213. request.allowsConstrainedNetworkAccess = false
  214. }
  215. if let requestModifier = options.requestModifier {
  216. // Modifies request before sending.
  217. requestModifier.modified(for: request) { result in
  218. guard let finalRequest = result else {
  219. done(.failure(KingfisherError.requestError(reason: .emptyRequest)))
  220. return
  221. }
  222. checkRequestAndDone(r: finalRequest)
  223. }
  224. } else {
  225. checkRequestAndDone(r: request)
  226. }
  227. }
  228. private func addDownloadTask(
  229. context: DownloadingContext,
  230. callback: SessionDataTask.TaskCallback
  231. ) -> DownloadTask
  232. {
  233. // Ready to start download. Add it to session task manager (`sessionHandler`)
  234. let downloadTask: DownloadTask
  235. if let existingTask = sessionDelegate.task(for: context.url) {
  236. downloadTask = sessionDelegate.append(existingTask, callback: callback)
  237. } else {
  238. let sessionDataTask = session.dataTask(with: context.request)
  239. sessionDataTask.priority = context.options.downloadPriority
  240. downloadTask = sessionDelegate.add(sessionDataTask, url: context.url, callback: callback)
  241. }
  242. return downloadTask
  243. }
  244. private func reportWillDownloadImage(url: URL, request: URLRequest) {
  245. delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request)
  246. }
  247. private func reportDidDownloadImageData(result: Result<(Data, URLResponse?), KingfisherError>, url: URL) {
  248. var response: URLResponse?
  249. var err: Error?
  250. do {
  251. response = try result.get().1
  252. } catch {
  253. err = error
  254. }
  255. self.delegate?.imageDownloader(
  256. self,
  257. didFinishDownloadingImageForURL: url,
  258. with: response,
  259. error: err
  260. )
  261. }
  262. private func reportDidProcessImage(
  263. result: Result<KFCrossPlatformImage, KingfisherError>, url: URL, response: URLResponse?
  264. )
  265. {
  266. if let image = try? result.get() {
  267. self.delegate?.imageDownloader(self, didDownload: image, for: url, with: response)
  268. }
  269. }
  270. private func startDownloadTask(
  271. context: DownloadingContext,
  272. callback: SessionDataTask.TaskCallback
  273. ) -> DownloadTask
  274. {
  275. let downloadTask = addDownloadTask(context: context, callback: callback)
  276. let sessionTask = downloadTask.sessionTask
  277. guard !sessionTask.started else {
  278. return downloadTask
  279. }
  280. sessionTask.onTaskDone.delegate(on: self) { (self, done) in
  281. // Underlying downloading finishes.
  282. // result: Result<(Data, URLResponse?)>, callbacks: [TaskCallback]
  283. let (result, callbacks) = done
  284. // Before processing the downloaded data.
  285. self.reportDidDownloadImageData(result: result, url: context.url)
  286. switch result {
  287. // Download finished. Now process the data to an image.
  288. case .success(let (data, response)):
  289. let processor = ImageDataProcessor(
  290. data: data, callbacks: callbacks, processingQueue: context.options.processingQueue
  291. )
  292. processor.onImageProcessed.delegate(on: self) { (self, done) in
  293. // `onImageProcessed` will be called for `callbacks.count` times, with each
  294. // `SessionDataTask.TaskCallback` as the input parameter.
  295. // result: Result<Image>, callback: SessionDataTask.TaskCallback
  296. let (result, callback) = done
  297. self.reportDidProcessImage(result: result, url: context.url, response: response)
  298. let imageResult = result.map { ImageLoadingResult(image: $0, url: context.url, originalData: data) }
  299. let queue = callback.options.callbackQueue
  300. queue.execute { callback.onCompleted?.call(imageResult) }
  301. }
  302. processor.process()
  303. case .failure(let error):
  304. callbacks.forEach { callback in
  305. let queue = callback.options.callbackQueue
  306. queue.execute { callback.onCompleted?.call(.failure(error)) }
  307. }
  308. }
  309. }
  310. reportWillDownloadImage(url: context.url, request: context.request)
  311. sessionTask.resume()
  312. return downloadTask
  313. }
  314. // MARK: Downloading Task
  315. /// Downloads an image with a URL and option. Invoked internally by Kingfisher. Subclasses must invoke super.
  316. ///
  317. /// - Parameters:
  318. /// - url: Target URL.
  319. /// - options: The options could control download behavior. See `KingfisherOptionsInfo`.
  320. /// - completionHandler: Called when the download progress finishes. This block will be called in the queue
  321. /// defined in `.callbackQueue` in `options` parameter.
  322. /// - Returns: A downloading task. You could call `cancel` on it to stop the download task.
  323. @discardableResult
  324. open func downloadImage(
  325. with url: URL,
  326. options: KingfisherParsedOptionsInfo,
  327. completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  328. {
  329. var downloadTask: DownloadTask?
  330. createDownloadContext(with: url, options: options) { result in
  331. switch result {
  332. case .success(let context):
  333. // `downloadTask` will be set if the downloading started immediately. This is the case when no request
  334. // modifier or a sync modifier (`ImageDownloadRequestModifier`) is used. Otherwise, when an
  335. // `AsyncImageDownloadRequestModifier` is used the returned `downloadTask` of this method will be `nil`
  336. // and the actual "delayed" task is given in `AsyncImageDownloadRequestModifier.onDownloadTaskStarted`
  337. // callback.
  338. downloadTask = self.startDownloadTask(
  339. context: context,
  340. callback: self.createTaskCallback(completionHandler, options: options)
  341. )
  342. if let modifier = options.requestModifier {
  343. modifier.onDownloadTaskStarted?(downloadTask)
  344. }
  345. case .failure(let error):
  346. options.callbackQueue.execute {
  347. completionHandler?(.failure(error))
  348. }
  349. }
  350. }
  351. return downloadTask
  352. }
  353. /// Downloads an image with a URL and option.
  354. ///
  355. /// - Parameters:
  356. /// - url: Target URL.
  357. /// - options: The options could control download behavior. See `KingfisherOptionsInfo`.
  358. /// - progressBlock: Called when the download progress updated. This block will be always be called in main queue.
  359. /// - completionHandler: Called when the download progress finishes. This block will be called in the queue
  360. /// defined in `.callbackQueue` in `options` parameter.
  361. /// - Returns: A downloading task. You could call `cancel` on it to stop the download task.
  362. @discardableResult
  363. open func downloadImage(
  364. with url: URL,
  365. options: KingfisherOptionsInfo? = nil,
  366. progressBlock: DownloadProgressBlock? = nil,
  367. completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  368. {
  369. var info = KingfisherParsedOptionsInfo(options)
  370. if let block = progressBlock {
  371. info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  372. }
  373. return downloadImage(
  374. with: url,
  375. options: info,
  376. completionHandler: completionHandler)
  377. }
  378. /// Downloads an image with a URL and option.
  379. ///
  380. /// - Parameters:
  381. /// - url: Target URL.
  382. /// - options: The options could control download behavior. See `KingfisherOptionsInfo`.
  383. /// - completionHandler: Called when the download progress finishes. This block will be called in the queue
  384. /// defined in `.callbackQueue` in `options` parameter.
  385. /// - Returns: A downloading task. You could call `cancel` on it to stop the download task.
  386. @discardableResult
  387. open func downloadImage(
  388. with url: URL,
  389. options: KingfisherOptionsInfo? = nil,
  390. completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  391. {
  392. downloadImage(
  393. with: url,
  394. options: KingfisherParsedOptionsInfo(options),
  395. completionHandler: completionHandler
  396. )
  397. }
  398. }
  399. // MARK: Cancelling Task
  400. extension ImageDownloader {
  401. /// Cancel all downloading tasks for this `ImageDownloader`. It will trigger the completion handlers
  402. /// for all not-yet-finished downloading tasks.
  403. ///
  404. /// If you need to only cancel a certain task, call `cancel()` on the `DownloadTask`
  405. /// returned by the downloading methods. If you need to cancel all `DownloadTask`s of a certain url,
  406. /// use `ImageDownloader.cancel(url:)`.
  407. public func cancelAll() {
  408. sessionDelegate.cancelAll()
  409. }
  410. /// Cancel all downloading tasks for a given URL. It will trigger the completion handlers for
  411. /// all not-yet-finished downloading tasks for the URL.
  412. ///
  413. /// - Parameter url: The URL which you want to cancel downloading.
  414. public func cancel(url: URL) {
  415. sessionDelegate.cancel(url: url)
  416. }
  417. }
  418. // Use the default implementation from extension of `AuthenticationChallengeResponsible`.
  419. extension ImageDownloader: AuthenticationChallengeResponsible {}
  420. // Use the default implementation from extension of `ImageDownloaderDelegate`.
  421. extension ImageDownloader: ImageDownloaderDelegate {}
  422. extension ImageDownloader {
  423. struct DownloadingContext {
  424. let url: URL
  425. let request: URLRequest
  426. let options: KingfisherParsedOptionsInfo
  427. }
  428. }