AsyncAwait.swift 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. // Copyright 2021 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. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  16. public extension StorageReference {
  17. /// Asynchronously downloads the object at the StorageReference to a Data object in memory.
  18. /// A Data object of the provided max size will be allocated, so ensure that the device has
  19. /// enough free memory to complete the download. For downloading large files, the `write`
  20. /// API may be a better option.
  21. ///
  22. /// - Parameters:
  23. /// - size: The maximum size in bytes to download. If the download exceeds this size,
  24. /// the task will be cancelled and an error will be thrown.
  25. /// - Throws:
  26. /// - An error if the operation failed, for example if the data exceeded `maxSize`.
  27. /// - Returns: Data object.
  28. func data(maxSize: Int64) async throws -> Data {
  29. return try await withCheckedThrowingContinuation { continuation in
  30. _ = self.getData(maxSize: maxSize) { result in
  31. continuation.resume(with: result)
  32. }
  33. }
  34. }
  35. /// Asynchronously uploads data to the currently specified StorageReference.
  36. /// This is not recommended for large files, and one should instead upload a file from disk
  37. /// from the Firebase Console.
  38. ///
  39. /// - Parameters:
  40. /// - uploadData: The Data to upload.
  41. /// - metadata: Optional StorageMetadata containing additional information (MIME type, etc.)
  42. /// about the object being uploaded.
  43. /// - onProgress: An optional closure function to return a `Progress` instance while the
  44. /// upload proceeds.
  45. /// - Throws:
  46. /// - An error if the operation failed, for example if Storage was unreachable.
  47. /// - Returns: StorageMetadata with additional information about the object being uploaded.
  48. func putDataAsync(_ uploadData: Data,
  49. metadata: StorageMetadata? = nil,
  50. onProgress: ((Progress?) -> Void)? = nil) async throws -> StorageMetadata {
  51. guard let onProgress = onProgress else {
  52. return try await withCheckedThrowingContinuation { continuation in
  53. self.putData(uploadData, metadata: metadata) { result in
  54. continuation.resume(with: result)
  55. }
  56. }
  57. }
  58. let uploadTask = putData(uploadData, metadata: metadata)
  59. return try await withCheckedThrowingContinuation { continuation in
  60. uploadTask.observe(.progress) {
  61. onProgress($0.progress)
  62. }
  63. uploadTask.observe(.success) { _ in
  64. continuation.resume(with: .success(uploadTask.metadata!))
  65. }
  66. uploadTask.observe(.failure) { snapshot in
  67. continuation.resume(with: .failure(
  68. snapshot.error ?? StorageError.internalError("Internal Storage Error in putDataAsync")
  69. ))
  70. }
  71. }
  72. }
  73. /// Asynchronously uploads a file to the currently specified StorageReference.
  74. /// `putDataAsync` should be used instead of `putFileAsync` in Extensions.
  75. ///
  76. /// - Parameters:
  77. /// - url: A URL representing the system file path of the object to be uploaded.
  78. /// - metadata: Optional StorageMetadata containing additional information (MIME type, etc.)
  79. /// about the object being uploaded.
  80. /// - onProgress: An optional closure function to return a `Progress` instance while the
  81. /// upload proceeds.
  82. /// - Throws:
  83. /// - An error if the operation failed, for example if no file was present at the specified
  84. /// `url`.
  85. /// - Returns: `StorageMetadata` with additional information about the object being uploaded.
  86. func putFileAsync(from url: URL,
  87. metadata: StorageMetadata? = nil,
  88. onProgress: ((Progress?) -> Void)? = nil) async throws -> StorageMetadata {
  89. guard let onProgress = onProgress else {
  90. return try await withCheckedThrowingContinuation { continuation in
  91. self.putFile(from: url, metadata: metadata) { result in
  92. continuation.resume(with: result)
  93. }
  94. }
  95. }
  96. let uploadTask = putFile(from: url, metadata: metadata)
  97. return try await withCheckedThrowingContinuation { continuation in
  98. uploadTask.observe(.progress) {
  99. onProgress($0.progress)
  100. }
  101. uploadTask.observe(.success) { _ in
  102. continuation.resume(with: .success(uploadTask.metadata!))
  103. }
  104. uploadTask.observe(.failure) { snapshot in
  105. continuation.resume(with: .failure(
  106. snapshot.error ?? StorageError.internalError("Internal Storage Error in putFileAsync")
  107. ))
  108. }
  109. }
  110. }
  111. /// Asynchronously downloads the object at the current path to a specified system filepath.
  112. ///
  113. /// - Parameters:
  114. /// - fileUrl: A URL representing the system file path of the object to be uploaded.
  115. /// - onProgress: An optional closure function to return a `Progress` instance while the
  116. /// download proceeds.
  117. /// - Throws:
  118. /// - An error if the operation failed, for example if Storage was unreachable
  119. /// or `fileURL` did not reference a valid path on disk.
  120. /// - Returns: A `URL` pointing to the file path of the downloaded file.
  121. func writeAsync(toFile fileURL: URL,
  122. onProgress: ((Progress?) -> Void)? = nil) async throws -> URL {
  123. guard let onProgress = onProgress else {
  124. return try await withCheckedThrowingContinuation { continuation in
  125. _ = self.write(toFile: fileURL) { result in
  126. continuation.resume(with: result)
  127. }
  128. }
  129. }
  130. let downloadTask = write(toFile: fileURL)
  131. return try await withCheckedThrowingContinuation { continuation in
  132. downloadTask.observe(.progress) {
  133. onProgress($0.progress)
  134. }
  135. downloadTask.observe(.success) { _ in
  136. continuation.resume(with: .success(fileURL))
  137. }
  138. downloadTask.observe(.failure) { snapshot in
  139. continuation.resume(with: .failure(
  140. snapshot.error ?? StorageError.internalError("Internal Storage Error in writeAsync")
  141. ))
  142. }
  143. }
  144. }
  145. /// List up to `maxResults` items (files) and prefixes (folders) under this StorageReference.
  146. ///
  147. /// "/" is treated as a path delimiter. Firebase Storage does not support unsupported object
  148. /// paths that end with "/" or contain two consecutive "/"s. All invalid objects in GCS will be
  149. /// filtered.
  150. ///
  151. /// Only available for projects using Firebase Rules Version 2.
  152. ///
  153. /// - Parameters:
  154. /// - maxResults The maximum number of results to return in a single page. Must be
  155. /// greater than 0 and at most 1000.
  156. /// - Throws:
  157. /// - An error if the operation failed, for example if Storage was unreachable
  158. /// or the storage reference referenced an invalid path.
  159. /// - Returns:
  160. /// - A `StorageListResult` containing the contents of the storage reference.
  161. func list(maxResults: Int64) async throws -> StorageListResult {
  162. typealias ListContinuation = CheckedContinuation<StorageListResult, Error>
  163. return try await withCheckedThrowingContinuation { (continuation: ListContinuation) in
  164. self.list(maxResults: maxResults) { result in
  165. continuation.resume(with: result)
  166. }
  167. }
  168. }
  169. /// List up to `maxResults` items (files) and prefixes (folders) under this StorageReference.
  170. ///
  171. /// "/" is treated as a path delimiter. Firebase Storage does not support unsupported object
  172. /// paths that end with "/" or contain two consecutive "/"s. All invalid objects in GCS will be
  173. /// filtered.
  174. ///
  175. /// Only available for projects using Firebase Rules Version 2.
  176. ///
  177. /// - Parameters:
  178. /// - maxResults The maximum number of results to return in a single page. Must be
  179. /// greater than 0 and at most 1000.
  180. /// - pageToken A page token from a previous call to list.
  181. /// - Throws:
  182. /// - An error if the operation failed, for example if Storage was unreachable
  183. /// or the storage reference referenced an invalid path.
  184. /// - Returns:
  185. /// - completion A `Result` enum with either the list or an `Error`.
  186. func list(maxResults: Int64, pageToken: String) async throws -> StorageListResult {
  187. typealias ListContinuation = CheckedContinuation<StorageListResult, Error>
  188. return try await withCheckedThrowingContinuation { (continuation: ListContinuation) in
  189. self.list(maxResults: maxResults, pageToken: pageToken) { result in
  190. continuation.resume(with: result)
  191. }
  192. }
  193. }
  194. }