ImageDownloader.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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 successful result of an image downloading process.
  33. public struct ImageLoadingResult: Sendable {
  34. /// The downloaded image.
  35. public let image: KFCrossPlatformImage
  36. /// The original URL of the image request.
  37. public let url: URL?
  38. /// The raw data received from the downloader.
  39. public let originalData: Data
  40. /// Creates an `ImageDownloadResult` object.
  41. ///
  42. /// - Parameters:
  43. /// - image: The image of the download result.
  44. /// - url: The URL from which the image was downloaded.
  45. /// - originalData: The binary data of the image.
  46. public init(image: KFCrossPlatformImage, url: URL? = nil, originalData: Data) {
  47. self.image = image
  48. self.url = url
  49. self.originalData = originalData
  50. }
  51. }
  52. /// Represents a task in the image downloading process.
  53. ///
  54. /// When a download starts in Kingfisher, the involved methods always return you an instance of ``DownloadTask``. If you
  55. /// need to cancel the task during the download process, you can keep a reference to the instance and call ``cancel()``
  56. /// on it.
  57. public final class DownloadTask: Sendable {
  58. init(sessionTask: SessionDataTask, cancelToken: SessionDataTask.CancelToken) {
  59. self.sessionTask = sessionTask
  60. self.cancelToken = cancelToken
  61. }
  62. /// The ``SessionDataTask`` object associated with this download task. Multiple `DownloadTask`s could refer to the
  63. /// same `sessionTask`. This is an optimization in Kingfisher to prevent multiple downloading tasks for the same
  64. /// URL resource simultaneously.
  65. ///
  66. /// When you call ``DownloadTask/cancel()``, this ``SessionDataTask`` and its cancellation token will be passed
  67. /// along. You can use them to identify the cancelled task.
  68. public let sessionTask: SessionDataTask
  69. /// The cancellation token used to cancel the task.
  70. ///
  71. /// This is solely for identifying the task when it is cancelled. To cancel a ``DownloadTask``, call
  72. /// ``DownloadTask/cancelToken``.
  73. public let cancelToken: SessionDataTask.CancelToken
  74. /// Cancel this single download task if it is running.
  75. ///
  76. /// This method will do nothing if this task is not running.
  77. ///
  78. /// In Kingfisher, there is an optimization to prevent starting another download task if the target URL is currently
  79. /// being downloaded. However, even when internally no new session task is created, a ``DownloadTask`` will still
  80. /// be created and returned when you call related methods. It will share the session downloading task with a
  81. /// previous task.
  82. ///
  83. /// In this case, if multiple ``DownloadTask``s share a single session download task, calling this method
  84. /// does not cancel the actual download process, since there are other `DownloadTask`s need it. It only removes
  85. /// `self` from the download list.
  86. ///
  87. /// > Tip: If you need to cancel all on-going ``DownloadTask``s of a certain URL, use
  88. /// ``ImageDownloader/cancel(url:)``. If you need to cancel all downloading tasks of an ``ImageDownloader``,
  89. /// use ``ImageDownloader/cancelAll()``.
  90. public func cancel() {
  91. sessionTask.cancel(token: cancelToken)
  92. }
  93. }
  94. actor CancellationDownloadTask {
  95. var task: DownloadTask?
  96. func setTask(_ task: DownloadTask?) {
  97. self.task = task
  98. }
  99. }
  100. extension DownloadTask {
  101. enum WrappedTask {
  102. case download(DownloadTask)
  103. case dataProviding
  104. func cancel() {
  105. switch self {
  106. case .download(let task): task.cancel()
  107. case .dataProviding: break
  108. }
  109. }
  110. var value: DownloadTask? {
  111. switch self {
  112. case .download(let task): return task
  113. case .dataProviding: return nil
  114. }
  115. }
  116. }
  117. }
  118. /// Represents a download manager for requesting an image with a URL from the server.
  119. open class ImageDownloader {
  120. // MARK: Singleton
  121. /// The default downloader.
  122. public static let `default` = ImageDownloader(name: "default")
  123. // MARK: Public Properties
  124. /// The duration before the download times out.
  125. ///
  126. /// If the download does not complete before this duration, the URL session will raise a timeout error, which
  127. /// Kingfisher wraps and forwards as a ``KingfisherError/ResponseErrorReason/URLSessionError(error:)``.
  128. ///
  129. /// The default timeout is set to 15 seconds.
  130. open var downloadTimeout: TimeInterval = 15.0
  131. /// A set of trusted hosts when receiving server trust challenges.
  132. ///
  133. /// A challenge with host name contained in this set will be ignored. You can use this set to specify the
  134. /// self-signed site. It only will be used if you don't specify the
  135. /// ``ImageDownloader/authenticationChallengeResponder``.
  136. ///
  137. /// > If ``ImageDownloader/authenticationChallengeResponder`` is set, this property will be ignored and the
  138. /// implementation of ``ImageDownloader/authenticationChallengeResponder`` will be used instead.
  139. open var trustedHosts: Set<String>?
  140. /// Use this to supply a configuration for the downloader.
  141. ///
  142. /// By default, `URLSessionConfiguration.ephemeral` will be used.
  143. ///
  144. /// You can modify the configuration before a downloading task begins. A configuration without persistent storage
  145. /// for caches is necessary for the downloader to function correctly.
  146. ///
  147. /// > Setting a new session delegate to the downloader will invalidate the existing session and create a new one
  148. /// > with the new value and the ``sessionDelegate``.
  149. open var sessionConfiguration = URLSessionConfiguration.ephemeral {
  150. didSet {
  151. session.invalidateAndCancel()
  152. session = URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil)
  153. }
  154. }
  155. /// The session delegate which is used to handle the session related tasks.
  156. ///
  157. /// > Setting a new session delegate to the downloader will invalidate the existing session and create a new one
  158. /// > with the new value and the ``sessionConfiguration``.
  159. open var sessionDelegate: SessionDelegate {
  160. didSet {
  161. session.invalidateAndCancel()
  162. session = URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil)
  163. setupSessionHandler()
  164. }
  165. }
  166. /// Whether the download requests should use pipeline or not.
  167. ///
  168. /// It sets the `httpShouldUsePipelining` of the `URLRequest` for the download task. Default is false.
  169. open var requestsUsePipelining = false
  170. /// The delegate of this `ImageDownloader` object.
  171. ///
  172. /// See the ``ImageDownloaderDelegate`` protocol for more information.
  173. open weak var delegate: ImageDownloaderDelegate?
  174. /// A responder for authentication challenges.
  175. ///
  176. /// The downloader forwards the received authentication challenge for the downloading session to this responder.
  177. /// See ``AuthenticationChallengeResponsible`` for more.
  178. open weak var authenticationChallengeResponder: AuthenticationChallengeResponsible?
  179. // The downloader name.
  180. private let name: String
  181. // The session bound to the downloader.
  182. private var session: URLSession
  183. // MARK: Initializers
  184. /// Creates a downloader with a given name.
  185. ///
  186. /// - Parameter name: The name for the downloader. It should not be empty.
  187. public init(name: String) {
  188. if name.isEmpty {
  189. fatalError("[Kingfisher] You should specify a name for the downloader. "
  190. + "A downloader with empty name is not permitted.")
  191. }
  192. self.name = name
  193. sessionDelegate = SessionDelegate()
  194. session = URLSession(
  195. configuration: sessionConfiguration,
  196. delegate: sessionDelegate,
  197. delegateQueue: nil)
  198. authenticationChallengeResponder = self
  199. setupSessionHandler()
  200. }
  201. deinit { session.invalidateAndCancel() }
  202. private func setupSessionHandler() {
  203. sessionDelegate.onReceiveSessionChallenge.delegate(on: self) { (self, invoke) in
  204. await (self.authenticationChallengeResponder ?? self).downloader(self, didReceive: invoke.1)
  205. }
  206. sessionDelegate.onReceiveSessionTaskChallenge.delegate(on: self) { (self, invoke) in
  207. await (self.authenticationChallengeResponder ?? self).downloader(self, task: invoke.1, didReceive: invoke.2)
  208. }
  209. sessionDelegate.onValidStatusCode.delegate(on: self) { (self, code) in
  210. (self.delegate ?? self).isValidStatusCode(code, for: self)
  211. }
  212. sessionDelegate.onResponseReceived.delegate(on: self) { (self, response) in
  213. await (self.delegate ?? self).imageDownloader(self, didReceive: response)
  214. }
  215. sessionDelegate.onDownloadingFinished.delegate(on: self) { (self, value) in
  216. let (url, result) = value
  217. do {
  218. let value = try result.get()
  219. self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: value, error: nil)
  220. } catch {
  221. self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: nil, error: error)
  222. }
  223. }
  224. sessionDelegate.onDidDownloadData.delegate(on: self) { (self, task) in
  225. (self.delegate ?? self).imageDownloader(self, didDownload: task.mutableData, with: task)
  226. }
  227. }
  228. // Wraps `completionHandler` to `onCompleted` respectively.
  229. private func createCompletionCallBack(_ completionHandler: ((DownloadResult) -> Void)?) -> Delegate<DownloadResult, Void>? {
  230. completionHandler.map { block -> Delegate<DownloadResult, Void> in
  231. let delegate = Delegate<Result<ImageLoadingResult, KingfisherError>, Void>()
  232. delegate.delegate(on: self) { (self, callback) in
  233. block(callback)
  234. }
  235. return delegate
  236. }
  237. }
  238. private func createTaskCallback(
  239. _ completionHandler: ((DownloadResult) -> Void)?,
  240. options: KingfisherParsedOptionsInfo
  241. ) -> SessionDataTask.TaskCallback
  242. {
  243. SessionDataTask.TaskCallback(
  244. onCompleted: createCompletionCallBack(completionHandler),
  245. options: options
  246. )
  247. }
  248. private func createDownloadContext(
  249. with url: URL,
  250. options: KingfisherParsedOptionsInfo,
  251. done: @escaping ((Result<DownloadingContext, KingfisherError>) -> Void)
  252. )
  253. {
  254. @Sendable func checkRequestAndDone(r: URLRequest) {
  255. // There is a possibility that request modifier changed the url to `nil` or empty.
  256. // In this case, throw an error.
  257. guard let url = r.url, !url.absoluteString.isEmpty else {
  258. done(.failure(KingfisherError.requestError(reason: .invalidURL(request: r))))
  259. return
  260. }
  261. done(.success(DownloadingContext(url: url, request: r, options: options)))
  262. }
  263. // Creates default request.
  264. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: downloadTimeout)
  265. request.httpShouldUsePipelining = requestsUsePipelining
  266. if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) , options.lowDataModeSource != nil {
  267. request.allowsConstrainedNetworkAccess = false
  268. }
  269. guard let requestModifier = options.requestModifier else {
  270. checkRequestAndDone(r: request)
  271. return
  272. }
  273. // Modifies request before sending.
  274. // FIXME: A temporary solution for keep the sync `ImageDownloadRequestModifier` behavior as before.
  275. // We should be able to combine two cases once the full async support can be introduced to Kingfisher.
  276. if let m = requestModifier as? ImageDownloadRequestModifier {
  277. guard let result = m.modified(for: request) else {
  278. done(.failure(KingfisherError.requestError(reason: .emptyRequest)))
  279. return
  280. }
  281. checkRequestAndDone(r: result)
  282. } else {
  283. Task { [request] in
  284. guard let result = await requestModifier.modified(for: request) else {
  285. done(.failure(KingfisherError.requestError(reason: .emptyRequest)))
  286. return
  287. }
  288. checkRequestAndDone(r: result)
  289. }
  290. }
  291. }
  292. private func addDownloadTask(
  293. context: DownloadingContext,
  294. callback: SessionDataTask.TaskCallback
  295. ) -> DownloadTask
  296. {
  297. // Ready to start download. Add it to session task manager (`sessionHandler`)
  298. let downloadTask: DownloadTask
  299. if let existingTask = sessionDelegate.task(for: context.url) {
  300. downloadTask = sessionDelegate.append(existingTask, callback: callback)
  301. } else {
  302. let sessionDataTask = session.dataTask(with: context.request)
  303. sessionDataTask.priority = context.options.downloadPriority
  304. downloadTask = sessionDelegate.add(sessionDataTask, url: context.url, callback: callback)
  305. }
  306. return downloadTask
  307. }
  308. private func reportWillDownloadImage(url: URL, request: URLRequest) {
  309. delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request)
  310. }
  311. private func reportDidDownloadImageData(result: Result<(Data, URLResponse?), KingfisherError>, url: URL) {
  312. var response: URLResponse?
  313. var err: Error?
  314. do {
  315. response = try result.get().1
  316. } catch {
  317. err = error
  318. }
  319. self.delegate?.imageDownloader(
  320. self,
  321. didFinishDownloadingImageForURL: url,
  322. with: response,
  323. error: err
  324. )
  325. }
  326. private func reportDidProcessImage(
  327. result: Result<KFCrossPlatformImage, KingfisherError>, url: URL, response: URLResponse?
  328. )
  329. {
  330. if let image = try? result.get() {
  331. self.delegate?.imageDownloader(self, didDownload: image, for: url, with: response)
  332. }
  333. }
  334. private func startDownloadTask(
  335. context: DownloadingContext,
  336. callback: SessionDataTask.TaskCallback
  337. ) -> DownloadTask
  338. {
  339. let downloadTask = addDownloadTask(context: context, callback: callback)
  340. let sessionTask = downloadTask.sessionTask
  341. guard !sessionTask.started else {
  342. return downloadTask
  343. }
  344. sessionTask.onTaskDone.delegate(on: self) { (self, done) in
  345. // Underlying downloading finishes.
  346. // result: Result<(Data, URLResponse?)>, callbacks: [TaskCallback]
  347. let (result, callbacks) = done
  348. // Before processing the downloaded data.
  349. self.reportDidDownloadImageData(result: result, url: context.url)
  350. switch result {
  351. // Download finished. Now process the data to an image.
  352. case .success(let (data, response)):
  353. let processor = ImageDataProcessor(
  354. data: data, callbacks: callbacks, processingQueue: context.options.processingQueue
  355. )
  356. processor.onImageProcessed.delegate(on: self) { (self, done) in
  357. // `onImageProcessed` will be called for `callbacks.count` times, with each
  358. // `SessionDataTask.TaskCallback` as the input parameter.
  359. // result: Result<Image>, callback: SessionDataTask.TaskCallback
  360. let (result, callback) = done
  361. self.reportDidProcessImage(result: result, url: context.url, response: response)
  362. let imageResult = result.map { ImageLoadingResult(image: $0, url: context.url, originalData: data) }
  363. let queue = callback.options.callbackQueue
  364. queue.execute { callback.onCompleted?.call(imageResult) }
  365. }
  366. processor.process()
  367. case .failure(let error):
  368. callbacks.forEach { callback in
  369. let queue = callback.options.callbackQueue
  370. queue.execute { callback.onCompleted?.call(.failure(error)) }
  371. }
  372. }
  373. }
  374. reportWillDownloadImage(url: context.url, request: context.request)
  375. sessionTask.resume()
  376. return downloadTask
  377. }
  378. // MARK: Downloading Task
  379. /// Downloads an image with a URL and options.
  380. ///
  381. /// - Parameters:
  382. /// - url: The target URL.
  383. /// - options: The options that can control download behavior. See ``KingfisherOptionsInfo``.
  384. /// - completionHandler: Called when the download progress finishes. This block will be called in the queue
  385. /// defined in ``KingfisherOptionsInfoItem/callbackQueue(_:)`` in the `options` parameter.
  386. ///
  387. /// - Returns: A downloading task. You can call ``DownloadTask/cancelToken`` on it to stop the download task.
  388. @discardableResult
  389. open func downloadImage(
  390. with url: URL,
  391. options: KingfisherParsedOptionsInfo,
  392. completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  393. {
  394. var downloadTask: DownloadTask?
  395. createDownloadContext(with: url, options: options) { result in
  396. switch result {
  397. case .success(let context):
  398. // `downloadTask` will be set if the downloading started immediately. This is the case when no request
  399. // modifier or a sync modifier (`ImageDownloadRequestModifier`) is used. Otherwise, when an
  400. // `AsyncImageDownloadRequestModifier` is used the returned `downloadTask` of this method will be `nil`
  401. // and the actual "delayed" task is given in `AsyncImageDownloadRequestModifier.onDownloadTaskStarted`
  402. // callback.
  403. downloadTask = self.startDownloadTask(
  404. context: context,
  405. callback: self.createTaskCallback(completionHandler, options: options)
  406. )
  407. if let modifier = options.requestModifier {
  408. modifier.onDownloadTaskStarted?(downloadTask)
  409. }
  410. case .failure(let error):
  411. options.callbackQueue.execute {
  412. completionHandler?(.failure(error))
  413. }
  414. }
  415. }
  416. return downloadTask
  417. }
  418. /// Downloads an image with a URL and options.
  419. ///
  420. /// - Parameters:
  421. /// - url: The target URL.
  422. /// - options: The options that can control download behavior. See ``KingfisherOptionsInfo``.
  423. /// - progressBlock: Called when the download progress is updated. This block will always be called on the main
  424. /// queue.
  425. /// - completionHandler: Called when the download progress finishes. This block will be called in the queue
  426. /// defined in ``KingfisherOptionsInfoItem/callbackQueue(_:)`` in the `options` parameter.
  427. ///
  428. /// - Returns: A downloading task. You can call ``DownloadTask/cancelToken`` on it to stop the download task.
  429. @discardableResult
  430. open func downloadImage(
  431. with url: URL,
  432. options: KingfisherOptionsInfo? = nil,
  433. progressBlock: DownloadProgressBlock? = nil,
  434. completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  435. {
  436. var info = KingfisherParsedOptionsInfo(options)
  437. if let block = progressBlock {
  438. info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  439. }
  440. return downloadImage(
  441. with: url,
  442. options: info,
  443. completionHandler: completionHandler)
  444. }
  445. /// Downloads an image with a URL and options.
  446. ///
  447. /// - Parameters:
  448. /// - url: The target URL.
  449. /// - options: The options that can control download behavior. See ``KingfisherOptionsInfo``.
  450. /// - completionHandler: Called when the download progress finishes. This block will be called in the queue
  451. /// defined in ``KingfisherOptionsInfoItem/callbackQueue(_:)`` in the `options` parameter.
  452. ///
  453. /// - Returns: A downloading task. You can call ``DownloadTask/cancelToken`` on it to stop the download task.
  454. @discardableResult
  455. open func downloadImage(
  456. with url: URL,
  457. options: KingfisherOptionsInfo? = nil,
  458. completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  459. {
  460. downloadImage(
  461. with: url,
  462. options: KingfisherParsedOptionsInfo(options),
  463. completionHandler: completionHandler
  464. )
  465. }
  466. }
  467. // Concurrency
  468. extension ImageDownloader {
  469. /// Downloads an image with a URL and option.
  470. ///
  471. /// - Parameters:
  472. /// - url: Target URL.
  473. /// - options: The options that can control download behavior. See ``KingfisherOptionsInfo``.
  474. /// - Returns: The image loading result.
  475. ///
  476. /// > To cancel the download task initialized by this method, cancel the `Task` where this method is running in.
  477. public func downloadImage(
  478. with url: URL,
  479. options: KingfisherParsedOptionsInfo
  480. ) async throws -> ImageLoadingResult {
  481. let task = CancellationDownloadTask()
  482. return try await withTaskCancellationHandler {
  483. try await withCheckedThrowingContinuation { continuation in
  484. let downloadTask = downloadImage(with: url, options: options) { result in
  485. continuation.resume(with: result)
  486. }
  487. if Task.isCancelled {
  488. downloadTask?.cancel()
  489. } else {
  490. Task {
  491. await task.setTask(downloadTask)
  492. }
  493. }
  494. }
  495. } onCancel: {
  496. Task {
  497. await task.task?.cancel()
  498. }
  499. }
  500. }
  501. /// Downloads an image with a URL and option.
  502. ///
  503. /// - Parameters:
  504. /// - url: Target URL.
  505. /// - options: The options that can control download behavior. See ``KingfisherOptionsInfo``.
  506. /// - progressBlock: Called when the download progress updated. This block will be always be called in main queue.
  507. /// - Returns: The image loading result.
  508. ///
  509. /// > To cancel the download task initialized by this method, cancel the `Task` where this method is running in.
  510. public func downloadImage(
  511. with url: URL,
  512. options: KingfisherOptionsInfo? = nil,
  513. progressBlock: DownloadProgressBlock? = nil
  514. ) async throws -> ImageLoadingResult
  515. {
  516. var info = KingfisherParsedOptionsInfo(options)
  517. if let block = progressBlock {
  518. info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  519. }
  520. return try await downloadImage(with: url, options: info)
  521. }
  522. /// Downloads an image with a URL and option.
  523. ///
  524. /// - Parameters:
  525. /// - url: Target URL.
  526. /// - options: The options that can control download behavior. See ``KingfisherOptionsInfo``.
  527. /// - Returns: The image loading result.
  528. ///
  529. /// > To cancel the download task initialized by this method, cancel the `Task` where this method is running in.
  530. public func downloadImage(
  531. with url: URL,
  532. options: KingfisherOptionsInfo? = nil
  533. ) async throws -> ImageLoadingResult
  534. {
  535. try await downloadImage(with: url, options: KingfisherParsedOptionsInfo(options))
  536. }
  537. }
  538. // MARK: Cancelling Task
  539. extension ImageDownloader {
  540. /// Cancel all downloading tasks for this ``ImageDownloader``.
  541. ///
  542. /// It will trigger the completion handlers for all not-yet-finished downloading tasks with a cancellation error.
  543. ///
  544. /// If you need to only cancel a certain task, call ``DownloadTask/cancel()`` on the task returned by the
  545. /// downloading methods. If you need to cancel all ``DownloadTask``s of a certain URL, use
  546. /// ``ImageDownloader/cancel(url:)``.
  547. public func cancelAll() {
  548. sessionDelegate.cancelAll()
  549. }
  550. /// Cancel all downloading tasks for a given URL.
  551. ///
  552. /// It will trigger the completion handlers for all not-yet-finished downloading tasks for the URL with a
  553. /// cancellation error.
  554. ///
  555. /// - Parameter url: The URL for which you want to cancel downloading.
  556. public func cancel(url: URL) {
  557. sessionDelegate.cancel(url: url)
  558. }
  559. }
  560. // Use the default implementation from extension of `AuthenticationChallengeResponsible`.
  561. extension ImageDownloader: AuthenticationChallengeResponsible {}
  562. // Use the default implementation from extension of `ImageDownloaderDelegate`.
  563. extension ImageDownloader: ImageDownloaderDelegate {}
  564. extension ImageDownloader {
  565. struct DownloadingContext {
  566. let url: URL
  567. let request: URLRequest
  568. let options: KingfisherParsedOptionsInfo
  569. }
  570. }