AsyncAwait.swift 9.1 KB

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