StorageDownloadTask.swift 6.9 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. * Downloads can be returned on completion with a completion handler, and can be monitored
  23. * by attaching observers, or controlled by calling `pause()`, `resume()`,
  24. * or `cancel()`.
  25. * Downloads can currently be returned as `Data` in memory, or as a `URL` to a file on disk.
  26. * Downloads are performed on a background queue, and callbacks are raised on the developer
  27. * specified `callbackQueue` in Storage, or the main queue if left unspecified.
  28. * Currently all uploads must be initiated and managed on the main queue.
  29. */
  30. @objc(FIRStorageDownloadTask)
  31. open class StorageDownloadTask: StorageObservableTask, StorageTaskManagement {
  32. /**
  33. * Prepares a task and begins execution.
  34. */
  35. @objc open func enqueue() {
  36. enqueueImplementation()
  37. }
  38. /**
  39. * Pauses a task currently in progress. Calling this on a paused task has no effect.
  40. */
  41. @objc open func pause() {
  42. dispatchQueue.async { [weak self] in
  43. guard let self = self else { return }
  44. if self.state == .paused || self.state == .pausing {
  45. return
  46. }
  47. self.state = .pausing
  48. // Use the resume callback to confirm pause status since it always runs after the last
  49. // NSURLSession update.
  50. self.fetcher?.resumeDataBlock = { [weak self] (data: Data) in
  51. guard let self = self else { return }
  52. self.downloadData = data
  53. self.state = .paused
  54. self.fire(for: .pause, snapshot: self.snapshot)
  55. }
  56. self.fetcher?.stopFetching()
  57. }
  58. }
  59. /**
  60. * Cancels a task.
  61. */
  62. @objc open func cancel() {
  63. let error = StorageErrorCode.error(withCode: .cancelled)
  64. cancel(withError: error)
  65. }
  66. /**
  67. * Resumes a paused task. Calling this on a running task has no effect.
  68. */
  69. @objc open func resume() {
  70. dispatchQueue.async { [weak self] in
  71. guard let self = self else { return }
  72. self.state = .resuming
  73. self.fire(for: .resume, snapshot: self.snapshot)
  74. self.state = .running
  75. self.enqueueImplementation(resumeWith: self.downloadData)
  76. }
  77. }
  78. private var fetcher: GTMSessionFetcher?
  79. private var fetcherCompletion: ((Data?, NSError?) -> Void)?
  80. internal var downloadData: Data?
  81. // Hold completion in object to force it to be retained until completion block is called.
  82. internal var completionData: ((Data?, Error?) -> Void)?
  83. internal var completionURL: ((URL?, Error?) -> Void)?
  84. // MARK: - Internal Implementations
  85. override internal init(reference: StorageReference,
  86. service: GTMSessionFetcherService,
  87. queue: DispatchQueue,
  88. file: URL?) {
  89. super.init(reference: reference, service: service, queue: queue, file: file)
  90. }
  91. deinit {
  92. self.fetcher?.stopFetching()
  93. }
  94. internal func enqueueImplementation(resumeWith resumeData: Data? = nil) {
  95. dispatchQueue.async { [weak self] in
  96. guard let self = self else { return }
  97. self.state = .queueing
  98. var request = self.baseRequest
  99. request.httpMethod = "GET"
  100. request.timeoutInterval = self.reference.storage.maxDownloadRetryTime
  101. var components = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)
  102. components?.query = "alt=media"
  103. request.url = components?.url
  104. var fetcher: GTMSessionFetcher
  105. if let resumeData = resumeData {
  106. fetcher = GTMSessionFetcher(downloadResumeData: resumeData)
  107. fetcher.comment = "Resuming DownloadTask"
  108. } else {
  109. fetcher = self.fetcherService.fetcher(with: request)
  110. fetcher.comment = "Resuming DownloadTask"
  111. }
  112. fetcher.maxRetryInterval = self.reference.storage.maxDownloadRetryInterval
  113. if let fileURL = self.fileURL {
  114. // Handle file downloads
  115. fetcher.destinationFileURL = fileURL
  116. fetcher.downloadProgressBlock = { [weak self] (bytesWritten: Int64,
  117. totalBytesWritten: Int64,
  118. totalBytesExpectedToWrite: Int64) in
  119. guard let self = self else { return }
  120. self.state = .progress
  121. self.progress.completedUnitCount = totalBytesWritten
  122. self.progress.totalUnitCount = totalBytesExpectedToWrite
  123. self.fire(for: .progress, snapshot: self.snapshot)
  124. self.state = .running
  125. }
  126. } else {
  127. // Handle data downloads
  128. fetcher.receivedProgressBlock = { [weak self] (bytesWritten: Int64,
  129. totalBytesWritten: Int64) in
  130. guard let self = self else { return }
  131. self.state = .progress
  132. self.progress.completedUnitCount = totalBytesWritten
  133. if let totalLength = self.fetcher?.response?.expectedContentLength {
  134. self.progress.totalUnitCount = totalLength
  135. }
  136. self.fire(for: .progress, snapshot: self.snapshot)
  137. self.state = .running
  138. }
  139. }
  140. self.fetcher = fetcher
  141. // Capture self here to retain until completion.
  142. self.fetcherCompletion = { [self] (data: Data?, error: NSError?) in
  143. defer {
  144. self.removeAllObservers()
  145. self.fetcherCompletion = nil
  146. }
  147. self.fire(for: .progress, snapshot: self.snapshot)
  148. // Handle potential issues with download
  149. if let error = error {
  150. self.state = .failed
  151. self.error = StorageErrorCode.error(withServerError: error, ref: self.reference)
  152. self.fire(for: .failure, snapshot: self.snapshot)
  153. return
  154. }
  155. // Download completed successfully, fire completion callbacks
  156. self.state = .success
  157. if let data = data {
  158. self.downloadData = data
  159. }
  160. self.fire(for: .success, snapshot: self.snapshot)
  161. }
  162. self.state = .running
  163. self.fetcher?.beginFetch { [self] data, error in
  164. self.fetcherCompletion?(data, error as? NSError)
  165. }
  166. }
  167. }
  168. internal func cancel(withError error: NSError) {
  169. dispatchQueue.async { [weak self] in
  170. guard let self = self else { return }
  171. self.state = .cancelled
  172. self.fetcher?.stopFetching()
  173. self.error = error
  174. self.fire(for: .failure, snapshot: self.snapshot)
  175. }
  176. }
  177. }