SessionDataTask.swift 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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`. It consists of an underlying `URLSessionDataTask` and
  28. /// an array of `TaskCallback`. Multiple `TaskCallback`s could be added for a single downloading data task.
  29. public class SessionDataTask {
  30. /// Represents the type of token which used for cancelling a task.
  31. public typealias CancelToken = Int
  32. struct TaskCallback {
  33. let onProgress: Delegate<(Int64, Int64), Void>?
  34. let onCompleted: Delegate<Result<ImageLoadingResult, KingfisherError>, Void>?
  35. let options: KingfisherParsedOptionsInfo
  36. }
  37. /// Downloaded raw data of current task.
  38. public private(set) var mutableData: Data
  39. /// The underlying download task. It is only for debugging purpose when you encountered an error. You should not
  40. /// modify the content of this task or start it yourself.
  41. public let task: URLSessionDataTask
  42. private var callbacksStore = [CancelToken: TaskCallback]()
  43. var callbacks: [SessionDataTask.TaskCallback] {
  44. lock.lock()
  45. defer { lock.unlock() }
  46. return Array(callbacksStore.values)
  47. }
  48. private var currentToken = 0
  49. private let lock = NSLock()
  50. let onTaskDone = Delegate<(Result<(Data, URLResponse?), KingfisherError>, [TaskCallback]), Void>()
  51. let onCallbackCancelled = Delegate<(CancelToken, TaskCallback), Void>()
  52. var started = false
  53. var containsCallbacks: Bool {
  54. // We should be able to use `task.state != .running` to check it.
  55. // However, in some rare cases, cancelling the task does not change
  56. // task state to `.cancelling` immediately, but still in `.running`.
  57. // So we need to check callbacks count to for sure that it is safe to remove the
  58. // task in delegate.
  59. return !callbacks.isEmpty
  60. }
  61. init(task: URLSessionDataTask) {
  62. self.task = task
  63. mutableData = Data()
  64. }
  65. func addCallback(_ callback: TaskCallback) -> CancelToken {
  66. lock.lock()
  67. defer { lock.unlock() }
  68. callbacksStore[currentToken] = callback
  69. defer { currentToken += 1 }
  70. return currentToken
  71. }
  72. func removeCallback(_ token: CancelToken) -> TaskCallback? {
  73. lock.lock()
  74. defer { lock.unlock() }
  75. if let callback = callbacksStore[token] {
  76. callbacksStore[token] = nil
  77. return callback
  78. }
  79. return nil
  80. }
  81. func resume() {
  82. guard !started else { return }
  83. started = true
  84. task.resume()
  85. }
  86. func cancel(token: CancelToken) {
  87. guard let callback = removeCallback(token) else {
  88. return
  89. }
  90. if callbacksStore.count == 0 {
  91. task.cancel()
  92. }
  93. onCallbackCancelled.call((token, callback))
  94. }
  95. func forceCancel() {
  96. for token in callbacksStore.keys {
  97. cancel(token: token)
  98. }
  99. }
  100. func didReceiveData(_ data: Data) {
  101. mutableData.append(data)
  102. }
  103. }