ImageDownloader.swift 27 KB

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