AsyncAwait.swift 8.6 KB

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