StorageDownloadTask.swift 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. weak var weakSelf = self
  43. dispatchQueue.async {
  44. guard let strongSelf = weakSelf else { return }
  45. if strongSelf.state == .paused || strongSelf.state == .pausing {
  46. return
  47. }
  48. strongSelf.state = .pausing
  49. // Use the resume callback to confirm pause status since it always runs after the last
  50. // NSURLSession update.
  51. strongSelf.fetcher?.resumeDataBlock = { (data: Data) in
  52. let strongerSelf = weakSelf
  53. strongerSelf?.downloadData = data
  54. strongerSelf?.state = .paused
  55. if let snapshot = strongerSelf?.snapshot {
  56. strongerSelf?.fire(for: .pause, snapshot: snapshot)
  57. }
  58. }
  59. strongSelf.fetcher?.stopFetching()
  60. }
  61. }
  62. /**
  63. * Cancels a task.
  64. */
  65. @objc open func cancel() {
  66. let error = StorageErrorCode.error(withCode: .cancelled)
  67. cancel(withError: error)
  68. }
  69. /**
  70. * Resumes a paused task. Calling this on a running task has no effect.
  71. */
  72. @objc open func resume() {
  73. weak var weakSelf = self
  74. dispatchQueue.async {
  75. weakSelf?.state = .resuming
  76. if let snapshot = weakSelf?.snapshot {
  77. weakSelf?.fire(for: .resume, snapshot: snapshot)
  78. }
  79. weakSelf?.state = .running
  80. weakSelf?.enqueueImplementation(resumeWith: self.downloadData)
  81. }
  82. }
  83. private var fetcher: GTMSessionFetcher?
  84. private var fetcherCompletion: ((Data?, NSError?) -> Void)?
  85. internal var downloadData: Data?
  86. // MARK: - Internal Implementations
  87. override internal 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. internal func enqueueImplementation(resumeWith resumeData: Data? = nil) {
  97. weak var weakSelf = self
  98. dispatchQueue.async {
  99. guard let strongSelf = weakSelf else { return }
  100. strongSelf.state = .queueing
  101. var request = strongSelf.baseRequest
  102. request.httpMethod = "GET"
  103. request.timeoutInterval = strongSelf.reference.storage.maxDownloadRetryTime
  104. var components = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)
  105. components?.query = "alt=media"
  106. request.url = components?.url
  107. var fetcher: GTMSessionFetcher
  108. if let resumeData = resumeData {
  109. fetcher = GTMSessionFetcher(downloadResumeData: resumeData)
  110. fetcher.comment = "Resuming DownloadTask"
  111. } else {
  112. fetcher = strongSelf.fetcherService.fetcher(with: request)
  113. fetcher.comment = "Resuming DownloadTask"
  114. }
  115. fetcher.maxRetryInterval = strongSelf.reference.storage.maxDownloadRetryInterval
  116. if let fileURL = strongSelf.fileURL {
  117. // Handle file downloads
  118. fetcher.destinationFileURL = fileURL
  119. fetcher.downloadProgressBlock = { (bytesWritten: Int64,
  120. totalBytesWritten: Int64,
  121. totalBytesExpectedToWrite: Int64) in
  122. weakSelf?.state = .progress
  123. weakSelf?.progress.completedUnitCount = totalBytesWritten
  124. weakSelf?.progress.totalUnitCount = totalBytesExpectedToWrite
  125. if let snapshot = weakSelf?.snapshot {
  126. weakSelf?.fire(for: .progress, snapshot: snapshot)
  127. }
  128. weakSelf?.state = .running
  129. }
  130. } else {
  131. // Handle data downloads
  132. fetcher.receivedProgressBlock = { (bytesWritten: Int64, totalBytesWritten: Int64) in
  133. weakSelf?.state = .progress
  134. weakSelf?.progress.completedUnitCount = totalBytesWritten
  135. if let totalLength = weakSelf?.fetcher?.response?.expectedContentLength {
  136. weakSelf?.progress.totalUnitCount = totalLength
  137. }
  138. if let snapshot = weakSelf?.snapshot {
  139. weakSelf?.fire(for: .progress, snapshot: snapshot)
  140. }
  141. weakSelf?.state = .running
  142. }
  143. }
  144. strongSelf.fetcher = fetcher
  145. strongSelf.fetcherCompletion = { (data: Data?, error: NSError?) in
  146. self.fire(for: .progress, snapshot: self.snapshot)
  147. // Handle potential issues with download
  148. if let error = error {
  149. self.state = .failed
  150. self.error = StorageErrorCode.error(withServerError: error, ref: self.reference)
  151. self.fire(for: .failure, snapshot: self.snapshot)
  152. self.removeAllObservers()
  153. self.fetcherCompletion = nil
  154. return
  155. }
  156. // Download completed successfully, fire completion callbacks
  157. self.state = .success
  158. if let data = data {
  159. self.downloadData = data
  160. }
  161. self.fire(for: .success, snapshot: self.snapshot)
  162. self.removeAllObservers()
  163. self.fetcherCompletion = nil
  164. }
  165. strongSelf.state = .running
  166. strongSelf.fetcher?.beginFetch { data, error in
  167. let strongSelf = weakSelf
  168. if let fetcherCompletion = strongSelf?.fetcherCompletion {
  169. fetcherCompletion(data, error as? NSError)
  170. }
  171. }
  172. }
  173. }
  174. internal func cancel(withError error: NSError) {
  175. weak var weakSelf = self
  176. dispatchQueue.async {
  177. weakSelf?.state = .cancelled
  178. weakSelf?.fetcher?.stopFetching()
  179. weakSelf?.error = error
  180. weakSelf?.fire(for: .failure, snapshot: self.snapshot)
  181. }
  182. }
  183. }