ImageDownloader.swift 26 KB

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