StorageDownloadTask.swift 6.8 KB

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