StorageDownloadTask.swift 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. // Copyright 2022 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. #if COCOAPODS
  16. import GTMSessionFetcher
  17. #else
  18. import GTMSessionFetcherCore
  19. #endif
  20. /**
  21. * `StorageDownloadTask` implements resumable downloads from an object in Firebase Storage.
  22. *
  23. * Downloads can be returned on completion with a completion handler, and can be monitored
  24. * by attaching observers, or controlled by calling `pause()`, `resume()`,
  25. * or `cancel()`.
  26. *
  27. * Downloads can currently be returned as `Data` in memory, or as a `URL` to a file on disk.
  28. *
  29. * Downloads are performed on a background queue, and callbacks are raised on the developer
  30. * specified `callbackQueue` in Storage, or the main queue if left unspecified.
  31. */
  32. @objc(FIRStorageDownloadTask)
  33. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  34. open class StorageDownloadTask: StorageObservableTask, StorageTaskManagement {
  35. /**
  36. * Prepares a task and begins execution.
  37. */
  38. @objc open func enqueue() {
  39. Task {
  40. await enqueueImplementation()
  41. }
  42. }
  43. /**
  44. * Pauses a task currently in progress. Calling this on a paused task has no effect.
  45. */
  46. @objc open func pause() {
  47. dispatchQueue.async { [weak self] in
  48. guard let self = self else { return }
  49. if self.state == .paused || self.state == .pausing {
  50. return
  51. }
  52. self.state = .pausing
  53. // Use the resume callback to confirm pause status since it always runs after the last
  54. // NSURLSession update.
  55. self.fetcher?.resumeDataBlock = { [weak self] (data: Data) in
  56. guard let self = self else { return }
  57. self.downloadData = data
  58. self.state = .paused
  59. self.fire(for: .pause, snapshot: self.snapshot)
  60. }
  61. self.fetcher?.stopFetching()
  62. }
  63. }
  64. /**
  65. * Cancels a task.
  66. */
  67. @objc open func cancel() {
  68. cancel(withError: StorageError.cancelled as NSError)
  69. }
  70. /**
  71. * Resumes a paused task. Calling this on a running task has no effect.
  72. */
  73. @objc open func resume() {
  74. dispatchQueue.async { [weak self] in
  75. guard let self = self else { return }
  76. self.state = .resuming
  77. self.fire(for: .resume, snapshot: self.snapshot)
  78. self.state = .running
  79. Task {
  80. await self.enqueueImplementation(resumeWith: self.downloadData)
  81. }
  82. }
  83. }
  84. private var fetcher: GTMSessionFetcher?
  85. var downloadData: Data?
  86. // Hold completion in object to force it to be retained until completion block is called.
  87. var completionData: ((Data?, Error?) -> Void)?
  88. var completionURL: ((URL?, Error?) -> Void)?
  89. // MARK: - Internal Implementations
  90. override init(reference: StorageReference,
  91. queue: DispatchQueue,
  92. file: URL?) {
  93. super.init(reference: reference, queue: queue, file: file)
  94. }
  95. deinit {
  96. self.fetcher?.stopFetching()
  97. }
  98. private func enqueueImplementation(resumeWith resumeData: Data? = nil) async {
  99. state = .queueing
  100. var request = baseRequest
  101. request.httpMethod = "GET"
  102. request.timeoutInterval = reference.storage.maxDownloadRetryTime
  103. var components = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)
  104. components?.query = "alt=media"
  105. request.url = components?.url
  106. var fetcher: GTMSessionFetcher
  107. if let resumeData {
  108. fetcher = GTMSessionFetcher(downloadResumeData: resumeData)
  109. fetcher.comment = "Resuming DownloadTask"
  110. } else {
  111. let fetcherService = await StorageFetcherService.shared.service(reference.storage)
  112. fetcher = fetcherService.fetcher(with: request)
  113. fetcher.comment = "Starting DownloadTask"
  114. }
  115. fetcher.maxRetryInterval = reference.storage.maxDownloadRetryInterval
  116. if let fileURL {
  117. // Handle file downloads
  118. fetcher.destinationFileURL = fileURL
  119. fetcher.downloadProgressBlock = { [weak self] (bytesWritten: Int64,
  120. totalBytesWritten: Int64,
  121. totalBytesExpectedToWrite: Int64) in
  122. guard let self = self else { return }
  123. self.state = .progress
  124. self.progress.completedUnitCount = totalBytesWritten
  125. self.progress.totalUnitCount = totalBytesExpectedToWrite
  126. self.fire(for: .progress, snapshot: self.snapshot)
  127. self.state = .running
  128. }
  129. } else {
  130. // Handle data downloads
  131. fetcher.receivedProgressBlock = { [weak self] (bytesWritten: Int64,
  132. totalBytesWritten: Int64) in
  133. guard let self = self else { return }
  134. self.state = .progress
  135. self.progress.completedUnitCount = totalBytesWritten
  136. if let totalLength = self.fetcher?.response?.expectedContentLength {
  137. self.progress.totalUnitCount = totalLength
  138. }
  139. self.fire(for: .progress, snapshot: self.snapshot)
  140. self.state = .running
  141. }
  142. }
  143. self.fetcher = fetcher
  144. state = .running
  145. do {
  146. let data = try await self.fetcher?.beginFetch()
  147. // Fire last progress updates
  148. fire(for: .progress, snapshot: snapshot)
  149. // Download completed successfully, fire completion callbacks
  150. state = .success
  151. if let data {
  152. downloadData = data
  153. }
  154. fire(for: .success, snapshot: snapshot)
  155. } catch {
  156. fire(for: .progress, snapshot: snapshot)
  157. state = .failed
  158. self.error = StorageErrorCode.error(
  159. withServerError: error as NSError,
  160. ref: reference
  161. )
  162. fire(for: .failure, snapshot: snapshot)
  163. }
  164. removeAllObservers()
  165. }
  166. func cancel(withError error: NSError) {
  167. dispatchQueue.async { [weak self] in
  168. guard let self = self else { return }
  169. self.state = .cancelled
  170. self.fetcher?.stopFetching()
  171. self.error = error
  172. self.fire(for: .failure, snapshot: self.snapshot)
  173. self.removeAllObservers()
  174. }
  175. }
  176. }