SessionDataTask.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. //
  2. // SessionDataTask.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2018/11/1.
  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. import Foundation
  27. /// Represents a session data task in ``ImageDownloader``.
  28. ///
  29. /// Essentially, a ``SessionDataTask`` wraps a `URLSessionDataTask` and manages the download data.
  30. /// It uses a ``SessionDataTask/CancelToken`` to track the task and manage its cancellation.
  31. public class SessionDataTask: @unchecked Sendable {
  32. /// Represents the type of token used for canceling a task.
  33. public typealias CancelToken = Int
  34. struct TaskCallback {
  35. let onCompleted: Delegate<Result<ImageLoadingResult, KingfisherError>, Void>?
  36. let options: KingfisherParsedOptionsInfo
  37. }
  38. private var _mutableData: Data
  39. /// The downloaded raw data of the current task.
  40. public var mutableData: Data {
  41. lock.lock()
  42. defer { lock.unlock() }
  43. return _mutableData
  44. }
  45. // This is a copy of `task.originalRequest?.url`. It is for obtaining race-safe behavior for a pitfall on iOS 13.
  46. // Ref: https://github.com/onevcat/Kingfisher/issues/1511
  47. public let originalURL: URL?
  48. /// The underlying download task.
  49. ///
  50. /// It is only for debugging purposes when you encounter an error. You should not modify the content of this task
  51. /// or start it yourself.
  52. public let task: URLSessionDataTask
  53. private var callbacksStore = [CancelToken: TaskCallback]()
  54. var callbacks: [SessionDataTask.TaskCallback] {
  55. lock.lock()
  56. defer { lock.unlock() }
  57. return Array(callbacksStore.values)
  58. }
  59. private var currentToken = 0
  60. private let lock = NSLock()
  61. private var _metrics: NetworkMetrics?
  62. /// The network metrics collected during the download task.
  63. public var metrics: NetworkMetrics? {
  64. lock.lock()
  65. defer { lock.unlock() }
  66. return _metrics
  67. }
  68. let onTaskDone = Delegate<(Result<(Data, URLResponse?), KingfisherError>, [TaskCallback]), Void>()
  69. let onCallbackCancelled = Delegate<(CancelToken, TaskCallback), Void>()
  70. var started = false
  71. var containsCallbacks: Bool {
  72. // We should be able to use `task.state != .running` to check it.
  73. // However, in some rare cases, cancelling the task does not change
  74. // task state to `.cancelling` immediately, but still in `.running`.
  75. // So we need to check callbacks count to for sure that it is safe to remove the
  76. // task in delegate.
  77. return !callbacks.isEmpty
  78. }
  79. init(task: URLSessionDataTask) {
  80. self.task = task
  81. self.originalURL = task.originalRequest?.url
  82. _mutableData = Data()
  83. }
  84. func addCallback(_ callback: TaskCallback) -> CancelToken {
  85. lock.lock()
  86. defer { lock.unlock() }
  87. callbacksStore[currentToken] = callback
  88. defer { currentToken += 1 }
  89. return currentToken
  90. }
  91. func removeCallback(_ token: CancelToken) -> TaskCallback? {
  92. lock.lock()
  93. defer { lock.unlock() }
  94. if let callback = callbacksStore[token] {
  95. callbacksStore[token] = nil
  96. return callback
  97. }
  98. return nil
  99. }
  100. @discardableResult
  101. func removeAllCallbacks() -> [TaskCallback] {
  102. lock.lock()
  103. defer { lock.unlock() }
  104. let callbacks = callbacksStore.values
  105. callbacksStore.removeAll()
  106. return Array(callbacks)
  107. }
  108. func resume() {
  109. guard !started else { return }
  110. started = true
  111. task.resume()
  112. }
  113. func cancel(token: CancelToken) {
  114. guard let callback = removeCallback(token) else {
  115. return
  116. }
  117. onCallbackCancelled.call((token, callback))
  118. }
  119. func forceCancel() {
  120. for token in callbacksStore.keys {
  121. cancel(token: token)
  122. }
  123. }
  124. func didReceiveData(_ data: Data) {
  125. lock.lock()
  126. defer { lock.unlock() }
  127. _mutableData.append(data)
  128. }
  129. func didCollectMetrics(_ metrics: NetworkMetrics) {
  130. lock.lock()
  131. defer { lock.unlock() }
  132. _metrics = metrics
  133. }
  134. }