You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

119 lines
4.1 KiB

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