StorageDownloadTask.swift 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. cancel(withError: StorageError.cancelled as NSError)
  66. }
  67. /**
  68. * Resumes a paused task. Calling this on a running task has no effect.
  69. */
  70. @objc open func resume() {
  71. dispatchQueue.async { [weak self] in
  72. guard let self = self else { return }
  73. self.state = .resuming
  74. self.fire(for: .resume, snapshot: self.snapshot)
  75. self.state = .running
  76. self.enqueueImplementation(resumeWith: self.downloadData)
  77. }
  78. }
  79. private var fetcher: GTMSessionFetcher?
  80. private var fetcherCompletion: ((Data?, NSError?) -> Void)?
  81. var downloadData: Data?
  82. // Hold completion in object to force it to be retained until completion block is called.
  83. var completionData: ((Data?, Error?) -> Void)?
  84. var completionURL: ((URL?, Error?) -> Void)?
  85. // MARK: - Internal Implementations
  86. override init(reference: StorageReference,
  87. service: GTMSessionFetcherService,
  88. queue: DispatchQueue,
  89. file: URL?) {
  90. super.init(reference: reference, service: service, queue: queue, file: file)
  91. }
  92. deinit {
  93. self.fetcher?.stopFetching()
  94. }
  95. func enqueueImplementation(resumeWith resumeData: Data? = nil) {
  96. dispatchQueue.async { [weak self] in
  97. guard let self = self else { return }
  98. self.state = .queueing
  99. var request = self.baseRequest
  100. request.httpMethod = "GET"
  101. request.timeoutInterval = self.reference.storage.maxDownloadRetryTime
  102. var components = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)
  103. components?.query = "alt=media"
  104. request.url = components?.url
  105. var fetcher: GTMSessionFetcher
  106. if let resumeData {
  107. fetcher = GTMSessionFetcher(downloadResumeData: resumeData)
  108. fetcher.comment = "Resuming DownloadTask"
  109. } else {
  110. fetcher = self.fetcherService.fetcher(with: request)
  111. fetcher.comment = "Starting DownloadTask"
  112. }
  113. fetcher.maxRetryInterval = self.reference.storage.maxDownloadRetryInterval
  114. if let fileURL {
  115. // Handle file downloads
  116. fetcher.destinationFileURL = fileURL
  117. fetcher.downloadProgressBlock = { [weak self] (bytesWritten: Int64,
  118. totalBytesWritten: Int64,
  119. totalBytesExpectedToWrite: Int64) in
  120. guard let self = self else { return }
  121. self.state = .progress
  122. self.progress.completedUnitCount = totalBytesWritten
  123. self.progress.totalUnitCount = totalBytesExpectedToWrite
  124. self.fire(for: .progress, snapshot: self.snapshot)
  125. self.state = .running
  126. }
  127. } else {
  128. // Handle data downloads
  129. fetcher.receivedProgressBlock = { [weak self] (bytesWritten: Int64,
  130. totalBytesWritten: Int64) in
  131. guard let self = self else { return }
  132. self.state = .progress
  133. self.progress.completedUnitCount = totalBytesWritten
  134. if let totalLength = self.fetcher?.response?.expectedContentLength {
  135. self.progress.totalUnitCount = totalLength
  136. }
  137. self.fire(for: .progress, snapshot: self.snapshot)
  138. self.state = .running
  139. }
  140. }
  141. self.fetcher = fetcher
  142. // Capture self here to retain until completion.
  143. self.fetcherCompletion = { [self] (data: Data?, error: NSError?) in
  144. defer {
  145. self.removeAllObservers()
  146. self.fetcherCompletion = nil
  147. }
  148. self.fire(for: .progress, snapshot: self.snapshot)
  149. // Handle potential issues with download
  150. if let error {
  151. self.state = .failed
  152. self.error = StorageErrorCode.error(withServerError: error, ref: self.reference)
  153. self.fire(for: .failure, snapshot: self.snapshot)
  154. return
  155. }
  156. // Download completed successfully, fire completion callbacks
  157. self.state = .success
  158. if let data {
  159. self.downloadData = data
  160. }
  161. self.fire(for: .success, snapshot: self.snapshot)
  162. }
  163. self.state = .running
  164. self.fetcher?.beginFetch { [self] data, error in
  165. self.fetcherCompletion?(data, error as? NSError)
  166. }
  167. }
  168. }
  169. func cancel(withError error: NSError) {
  170. dispatchQueue.async { [weak self] in
  171. guard let self = self else { return }
  172. self.state = .cancelled
  173. self.fetcher?.stopFetching()
  174. self.error = error
  175. self.fire(for: .failure, snapshot: self.snapshot)
  176. }
  177. }
  178. }