StorageReference.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. /// `StorageReference` represents a reference to a Google Cloud Storage object. Developers can
  16. /// upload and download objects, as well as get/set object metadata, and delete an object at the
  17. /// path. See the [Cloud docs](https://cloud.google.com/storage/) for more details.
  18. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  19. @objc(FIRStorageReference) open class StorageReference: NSObject {
  20. // MARK: - Public APIs
  21. /// The `Storage` service object which created this reference.
  22. @objc public let storage: Storage
  23. /// The name of the Google Cloud Storage bucket associated with this reference.
  24. /// For example, in `gs://bucket/path/to/object.txt`, the bucket would be 'bucket'.
  25. @objc public var bucket: String {
  26. return path.bucket
  27. }
  28. /// The full path to this object, not including the Google Cloud Storage bucket.
  29. /// In `gs://bucket/path/to/object.txt`, the full path would be: `path/to/object.txt`.
  30. @objc public var fullPath: String {
  31. return path.object ?? ""
  32. }
  33. /// The short name of the object associated with this reference.
  34. ///
  35. /// In `gs://bucket/path/to/object.txt`, the name of the object would be `object.txt`.
  36. @objc public var name: String {
  37. return (path.object as? NSString)?.lastPathComponent ?? ""
  38. }
  39. /// Creates a new `StorageReference` pointing to the root object.
  40. /// - Returns: A new `StorageReference` pointing to the root object.
  41. @objc open func root() -> StorageReference {
  42. return StorageReference(storage: storage, path: path.root())
  43. }
  44. /// Creates a new `StorageReference` pointing to the parent of the current reference
  45. /// or `nil` if this instance references the root location.
  46. /// ```
  47. /// For example:
  48. /// path = foo/bar/baz parent = foo/bar
  49. /// path = foo parent = (root)
  50. /// path = (root) parent = nil
  51. /// ```
  52. /// - Returns: A new `StorageReference` pointing to the parent of the current reference.
  53. @objc open func parent() -> StorageReference? {
  54. guard let parentPath = path.parent() else {
  55. return nil
  56. }
  57. return StorageReference(storage: storage, path: parentPath)
  58. }
  59. /// Creates a new `StorageReference` pointing to a child object of the current reference.
  60. /// ```
  61. /// path = foo child = bar newPath = foo/bar
  62. /// path = foo/bar child = baz ntask.impl.snapshotwPath = foo/bar/baz
  63. /// All leading and trailing slashes will be removed, and consecutive slashes will be
  64. /// compressed to single slashes. For example:
  65. /// child = /foo/bar newPath = foo/bar
  66. /// child = foo/bar/ newPath = foo/bar
  67. /// child = foo///bar newPath = foo/bar
  68. /// ```
  69. ///
  70. /// - Parameter path: The path to append to the current path.
  71. /// - Returns: A new `StorageReference` pointing to a child location of the current reference.
  72. @objc(child:) open func child(_ path: String) -> StorageReference {
  73. return StorageReference(storage: storage, path: self.path.child(path))
  74. }
  75. // MARK: - Uploads
  76. /// Asynchronously uploads data to the currently specified `StorageReference`,
  77. /// without additional metadata.
  78. /// This is not recommended for large files, and one should instead upload a file from disk.
  79. /// - Parameters:
  80. /// - uploadData: The data to upload.
  81. /// - metadata: `StorageMetadata` containing additional information (MIME type, etc.)
  82. /// about the object being uploaded.
  83. /// - Returns: An instance of `StorageUploadTask`, which can be used to monitor or manage the
  84. /// upload.
  85. @objc(putData:metadata:)
  86. @discardableResult
  87. open func putData(_ uploadData: Data, metadata: StorageMetadata? = nil) -> StorageUploadTask {
  88. return putData(uploadData, metadata: metadata, completion: nil)
  89. }
  90. /// Asynchronously uploads data to the currently specified `StorageReference`.
  91. /// This is not recommended for large files, and one should instead upload a file from disk.
  92. /// - Parameter uploadData The data to upload.
  93. /// - Returns: An instance of `StorageUploadTask`, which can be used to monitor or manage the
  94. /// upload.
  95. @objc(putData:) @discardableResult open func __putData(_ uploadData: Data) -> StorageUploadTask {
  96. return putData(uploadData, metadata: nil, completion: nil)
  97. }
  98. /// Asynchronously uploads data to the currently specified `StorageReference`.
  99. /// This is not recommended for large files, and one should instead upload a file from disk.
  100. /// - Parameters:
  101. /// - uploadData: The data to upload.
  102. /// - metadata: `StorageMetadata` containing additional information (MIME type, etc.)
  103. /// about the object being uploaded.
  104. /// - completion: A closure that either returns the object metadata on success,
  105. /// or an error on failure.
  106. /// - Returns: An instance of `StorageUploadTask`, which can be used to monitor or manage the
  107. /// upload.
  108. @objc(putData:metadata:completion:) @discardableResult
  109. open func putData(_ uploadData: Data,
  110. metadata: StorageMetadata? = nil,
  111. completion: ((_: StorageMetadata?, _: Error?) -> Void)?) -> StorageUploadTask {
  112. let putMetadata = metadata ?? StorageMetadata()
  113. if let path = path.object {
  114. putMetadata.path = path
  115. putMetadata.name = (path as NSString).lastPathComponent as String
  116. }
  117. let task = StorageUploadTask(reference: self,
  118. queue: storage.dispatchQueue,
  119. data: uploadData,
  120. metadata: putMetadata)
  121. startAndObserveUploadTask(task: task, completion: completion)
  122. return task
  123. }
  124. /// Asynchronously uploads a file to the currently specified `StorageReference`.
  125. /// - Parameters:
  126. /// - fileURL: A URL representing the system file path of the object to be uploaded.
  127. /// - metadata: `StorageMetadata` containing additional information (MIME type, etc.)
  128. /// about the object being uploaded.
  129. /// - Returns: An instance of `StorageUploadTask`, which can be used to monitor or manage the
  130. /// upload.
  131. @objc(putFile:metadata:) @discardableResult
  132. open func putFile(from fileURL: URL, metadata: StorageMetadata? = nil) -> StorageUploadTask {
  133. return putFile(from: fileURL, metadata: metadata, completion: nil)
  134. }
  135. /// Asynchronously uploads a file to the currently specified `StorageReference`,
  136. /// without additional metadata.
  137. /// @param fileURL A URL representing the system file path of the object to be uploaded.
  138. /// @return An instance of StorageUploadTask, which can be used to monitor or manage the upload.
  139. @objc(putFile:) @discardableResult open func __putFile(from fileURL: URL) -> StorageUploadTask {
  140. return putFile(from: fileURL, metadata: nil, completion: nil)
  141. }
  142. /// Asynchronously uploads a file to the currently specified `StorageReference`.
  143. /// - Parameters:
  144. /// - fileURL: A URL representing the system file path of the object to be uploaded.
  145. /// - metadata: `StorageMetadata` containing additional information (MIME type, etc.)
  146. /// about the object being uploaded.
  147. /// - completion: A completion block that either returns the object metadata on success,
  148. /// or an error on failure.
  149. /// - Returns: An instance of `StorageUploadTask`, which can be used to monitor or manage the
  150. /// upload.
  151. @objc(putFile:metadata:completion:) @discardableResult
  152. open func putFile(from fileURL: URL,
  153. metadata: StorageMetadata? = nil,
  154. completion: ((_: StorageMetadata?, _: Error?) -> Void)?) -> StorageUploadTask {
  155. let putMetadata: StorageMetadata = metadata ?? StorageMetadata()
  156. if let path = path.object {
  157. putMetadata.path = path
  158. putMetadata.name = (path as NSString).lastPathComponent as String
  159. }
  160. let task = StorageUploadTask(reference: self,
  161. queue: storage.dispatchQueue,
  162. file: fileURL,
  163. metadata: putMetadata)
  164. startAndObserveUploadTask(task: task, completion: completion)
  165. return task
  166. }
  167. // MARK: - Downloads
  168. /// Asynchronously downloads the object at the `StorageReference` to a `Data` instance in memory.
  169. /// A `Data` buffer of the provided max size will be allocated, so ensure that the device has
  170. /// enough free
  171. /// memory to complete the download. For downloading large files, `write(toFile:)` may be a better
  172. /// option.
  173. /// - Parameters:
  174. /// - maxSize: The maximum size in bytes to download. If the download exceeds this size,
  175. /// the task will be cancelled and an error will be returned.
  176. /// - completion: A completion block that either returns the object data on success,
  177. /// or an error on failure.
  178. /// - Returns: A `StorageDownloadTask` that can be used to monitor or manage the download.
  179. @objc(dataWithMaxSize:completion:) @discardableResult
  180. open func getData(maxSize: Int64,
  181. completion: @escaping ((_: Data?, _: Error?) -> Void)) -> StorageDownloadTask {
  182. let task = StorageDownloadTask(reference: self,
  183. queue: storage.dispatchQueue,
  184. file: nil)
  185. task.completionData = completion
  186. let callbackQueue = storage.callbackQueue
  187. task.observe(.success) { snapshot in
  188. let error = self.checkSizeOverflow(task: snapshot.task, maxSize: maxSize)
  189. callbackQueue.async {
  190. if let completion = task.completionData {
  191. let data = error == nil ? task.downloadData : nil
  192. completion(data, error)
  193. task.completionData = nil
  194. }
  195. }
  196. }
  197. task.observe(.failure) { snapshot in
  198. callbackQueue.async {
  199. task.completionData?(nil, snapshot.error)
  200. task.completionData = nil
  201. }
  202. }
  203. task.observe(.progress) { snapshot in
  204. if let error = self.checkSizeOverflow(task: snapshot.task, maxSize: maxSize) {
  205. task.cancel(withError: error)
  206. }
  207. }
  208. task.enqueue()
  209. return task
  210. }
  211. /// Asynchronously retrieves a long lived download URL with a revokable token.
  212. /// This can be used to share the file with others, but can be revoked by a developer
  213. /// in the Firebase Console.
  214. /// - Parameter completion: A completion block that either returns the URL on success,
  215. /// or an error on failure.
  216. @objc(downloadURLWithCompletion:)
  217. open func downloadURL(completion: @escaping ((_: URL?, _: Error?) -> Void)) {
  218. StorageGetDownloadURLTask.getDownloadURLTask(reference: self,
  219. queue: storage.dispatchQueue,
  220. completion: completion)
  221. }
  222. /// Asynchronously retrieves a long lived download URL with a revokable token.
  223. /// This can be used to share the file with others, but can be revoked by a developer
  224. /// in the Firebase Console.
  225. /// - Throws: An error if the download URL could not be retrieved.
  226. /// - Returns: The URL on success.
  227. open func downloadURL() async throws -> URL {
  228. return try await withCheckedThrowingContinuation { continuation in
  229. self.downloadURL { result in
  230. continuation.resume(with: result)
  231. }
  232. }
  233. }
  234. /// Asynchronously downloads the object at the current path to a specified system filepath.
  235. /// - Parameter fileURL: A file system URL representing the path the object should be downloaded
  236. /// to.
  237. /// - Returns A `StorageDownloadTask` that can be used to monitor or manage the download.
  238. @objc(writeToFile:) @discardableResult
  239. open func write(toFile fileURL: URL) -> StorageDownloadTask {
  240. return write(toFile: fileURL, completion: nil)
  241. }
  242. /// Asynchronously downloads the object at the current path to a specified system filepath.
  243. /// - Parameters:
  244. /// - fileURL: A file system URL representing the path the object should be downloaded to.
  245. /// - completion: A closure that fires when the file download completes, passed either
  246. /// a URL pointing to the file path of the downloaded file on success,
  247. /// or an error on failure.
  248. /// - Returns: A `StorageDownloadTask` that can be used to monitor or manage the download.
  249. @objc(writeToFile:completion:) @discardableResult
  250. open func write(toFile fileURL: URL,
  251. completion: ((_: URL?, _: Error?) -> Void)?) -> StorageDownloadTask {
  252. let task = StorageDownloadTask(reference: self,
  253. queue: storage.dispatchQueue,
  254. file: fileURL)
  255. if let completion {
  256. task.completionURL = completion
  257. let callbackQueue = storage.callbackQueue
  258. task.observe(.success) { snapshot in
  259. callbackQueue.async {
  260. task.completionURL?(fileURL, nil)
  261. task.completionURL = nil
  262. }
  263. }
  264. task.observe(.failure) { snapshot in
  265. callbackQueue.async {
  266. task.completionURL?(nil, snapshot.error)
  267. task.completionURL = nil
  268. }
  269. }
  270. }
  271. task.enqueue()
  272. return task
  273. }
  274. // MARK: - List Support
  275. /// Lists all items (files) and prefixes (folders) under this `StorageReference`.
  276. ///
  277. /// This is a helper method for calling `list()` repeatedly until there are no more results.
  278. ///
  279. /// Consistency of the result is not guaranteed if objects are inserted or removed while this
  280. /// operation is executing. All results are buffered in memory.
  281. ///
  282. /// `listAll(completion:)` is only available for projects using Firebase Rules Version 2.
  283. /// - Parameter completion: A completion handler that will be invoked with all items and prefixes
  284. /// under
  285. /// the current `StorageReference`.
  286. @objc(listAllWithCompletion:)
  287. open func listAll(completion: @escaping ((_: StorageListResult?, _: Error?) -> Void)) {
  288. var prefixes = [StorageReference]()
  289. var items = [StorageReference]()
  290. weak var weakSelf = self
  291. var paginatedCompletion: ((_: StorageListResult?, _: Error?) -> Void)?
  292. paginatedCompletion = { (_ listResult: StorageListResult?, _ error: Error?) in
  293. if let error {
  294. completion(nil, error)
  295. return
  296. }
  297. guard let strongSelf = weakSelf else { return }
  298. guard let listResult = listResult else {
  299. fatalError("internal error: both listResult and error are nil")
  300. }
  301. prefixes.append(contentsOf: listResult.prefixes)
  302. items.append(contentsOf: listResult.items)
  303. if let pageToken = listResult.pageToken {
  304. StorageListTask.listTask(reference: strongSelf,
  305. queue: strongSelf.storage.dispatchQueue,
  306. pageSize: nil,
  307. previousPageToken: pageToken,
  308. completion: paginatedCompletion)
  309. } else {
  310. let result = StorageListResult(withPrefixes: prefixes, items: items, pageToken: nil)
  311. // Break the retain cycle we set up indirectly by passing the callback to `nextPage`.
  312. paginatedCompletion = nil
  313. completion(result, nil)
  314. }
  315. }
  316. StorageListTask.listTask(reference: self,
  317. queue: storage.dispatchQueue,
  318. pageSize: nil,
  319. previousPageToken: nil,
  320. completion: paginatedCompletion)
  321. }
  322. /// Lists all items (files) and prefixes (folders) under this StorageReference.
  323. /// This is a helper method for calling list() repeatedly until there are no more results.
  324. /// Consistency of the result is not guaranteed if objects are inserted or removed while this
  325. /// operation is executing. All results are buffered in memory.
  326. /// `listAll()` is only available for projects using Firebase Rules Version 2.
  327. /// - Throws: An error if the list operation failed.
  328. /// - Returns: All items and prefixes under the current `StorageReference`.
  329. open func listAll() async throws -> StorageListResult {
  330. return try await withCheckedThrowingContinuation { continuation in
  331. self.listAll { result in
  332. continuation.resume(with: result)
  333. }
  334. }
  335. }
  336. /// List up to `maxResults` items (files) and prefixes (folders) under this StorageReference.
  337. ///
  338. /// "/" is treated as a path delimiter. Firebase Storage does not support unsupported object
  339. /// paths that end with "/" or contain two consecutive "/"s. All invalid objects in GCS will be
  340. /// filtered.
  341. ///
  342. /// Only available for projects using Firebase Rules Version 2.
  343. /// - Parameters:
  344. /// - maxResults: The maximum number of results to return in a single page. Must be
  345. /// greater than 0 and at most 1000.
  346. /// - completion: A completion handler that will be invoked with up to `maxResults` items and
  347. /// prefixes under the current `StorageReference`.
  348. @objc(listWithMaxResults:completion:)
  349. open func list(maxResults: Int64,
  350. completion: @escaping ((_: StorageListResult?, _: Error?) -> Void)) {
  351. if maxResults <= 0 || maxResults > 1000 {
  352. completion(nil, StorageError.invalidArgument(
  353. message: "Argument 'maxResults' must be between 1 and 1000 inclusive."
  354. ))
  355. } else {
  356. StorageListTask.listTask(reference: self,
  357. queue: storage.dispatchQueue,
  358. pageSize: maxResults,
  359. previousPageToken: nil,
  360. completion: completion)
  361. }
  362. }
  363. /// Resumes a previous call to `list(maxResults:completion:)`, starting after a pagination token.
  364. ///
  365. /// Returns the next set of items (files) and prefixes (folders) under this `StorageReference`.
  366. ///
  367. /// "/" is treated as a path delimiter. Storage does not support unsupported object
  368. /// paths that end with "/" or contain two consecutive "/"s. All invalid objects in GCS will be
  369. /// filtered.
  370. ///
  371. /// `list(maxResults:pageToken:completion:)`is only available for projects using Firebase Rules
  372. /// Version 2.
  373. /// - Parameters:
  374. /// - maxResults: The maximum number of results to return in a single page. Must be greater
  375. /// than 0 and at most 1000.
  376. /// - pageToken: A page token from a previous call to list.
  377. /// - completion: A completion handler that will be invoked with the next items and prefixes
  378. /// under the current StorageReference.
  379. @objc(listWithMaxResults:pageToken:completion:)
  380. open func list(maxResults: Int64,
  381. pageToken: String,
  382. completion: @escaping ((_: StorageListResult?, _: Error?) -> Void)) {
  383. if maxResults <= 0 || maxResults > 1000 {
  384. completion(nil, StorageError.invalidArgument(
  385. message: "Argument 'maxResults' must be between 1 and 1000 inclusive."
  386. ))
  387. } else {
  388. StorageListTask.listTask(reference: self,
  389. queue: storage.dispatchQueue,
  390. pageSize: maxResults,
  391. previousPageToken: pageToken,
  392. completion: completion)
  393. }
  394. }
  395. // MARK: - Metadata Operations
  396. /// Retrieves metadata associated with an object at the current path.
  397. /// - Parameter completion: A completion block which returns the object metadata on success,
  398. /// or an error on failure.
  399. @objc(metadataWithCompletion:)
  400. open func getMetadata(completion: @escaping ((_: StorageMetadata?, _: Error?) -> Void)) {
  401. StorageGetMetadataTask.getMetadataTask(reference: self,
  402. queue: storage.dispatchQueue,
  403. completion: completion)
  404. }
  405. /// Retrieves metadata associated with an object at the current path.
  406. /// - Throws: An error if the object metadata could not be retrieved.
  407. /// - Returns: The object metadata on success.
  408. open func getMetadata() async throws -> StorageMetadata {
  409. return try await withCheckedThrowingContinuation { continuation in
  410. self.getMetadata { result in
  411. continuation.resume(with: result)
  412. }
  413. }
  414. }
  415. /// Updates the metadata associated with an object at the current path.
  416. /// - Parameters:
  417. /// - metadata: A `StorageMetadata` object with the metadata to update.
  418. /// - completion: A completion block which returns the `StorageMetadata` on success,
  419. /// or an error on failure.
  420. @objc(updateMetadata:completion:)
  421. open func updateMetadata(_ metadata: StorageMetadata,
  422. completion: ((_: StorageMetadata?, _: Error?) -> Void)?) {
  423. StorageUpdateMetadataTask.updateMetadataTask(reference: self,
  424. queue: storage.dispatchQueue,
  425. metadata: metadata,
  426. completion: completion)
  427. }
  428. /// Updates the metadata associated with an object at the current path.
  429. /// - Parameter metadata: A `StorageMetadata` object with the metadata to update.
  430. /// - Throws: An error if the metadata update operation failed.
  431. /// - Returns: The object metadata on success.
  432. open func updateMetadata(_ metadata: StorageMetadata) async throws -> StorageMetadata {
  433. return try await withCheckedThrowingContinuation { continuation in
  434. self.updateMetadata(metadata) { result in
  435. continuation.resume(with: result)
  436. }
  437. }
  438. }
  439. // MARK: - Delete
  440. /// Deletes the object at the current path.
  441. /// - Parameter completion: A completion block which returns a nonnull error on failure.
  442. @objc(deleteWithCompletion:)
  443. open func delete(completion: ((_: Error?) -> Void)?) {
  444. let completionWrap = { (_: Data?, error: Error?) in
  445. if let completion {
  446. completion(error)
  447. }
  448. }
  449. StorageDeleteTask.deleteTask(reference: self,
  450. queue: storage.dispatchQueue,
  451. completion: completionWrap)
  452. }
  453. /// Deletes the object at the current path.
  454. /// - Throws: An error if the delete operation failed.
  455. open func delete() async throws {
  456. return try await withCheckedThrowingContinuation { continuation in
  457. self.delete { error in
  458. if let error {
  459. continuation.resume(throwing: error)
  460. } else {
  461. continuation.resume()
  462. }
  463. }
  464. }
  465. }
  466. // MARK: - NSObject overrides
  467. /// NSObject override
  468. @objc override open func copy() -> Any {
  469. return StorageReference(storage: storage, path: path)
  470. }
  471. /// NSObject override
  472. @objc override open func isEqual(_ object: Any?) -> Bool {
  473. guard let ref = object as? StorageReference else {
  474. return false
  475. }
  476. return storage == ref.storage && path == ref.path
  477. }
  478. /// NSObject override
  479. @objc override public var hash: Int {
  480. return storage.hash ^ path.bucket.hashValue
  481. }
  482. /// NSObject override
  483. @objc override public var description: String {
  484. return "gs://\(path.bucket)/\(path.object ?? "")"
  485. }
  486. // MARK: - Internal APIs
  487. /// The current path which points to an object in the Google Cloud Storage bucket.
  488. let path: StoragePath
  489. override init() {
  490. storage = Storage.storage()
  491. let storageBucket = storage.app.options.storageBucket!
  492. path = StoragePath(with: storageBucket)
  493. }
  494. init(storage: Storage, path: StoragePath) {
  495. self.storage = storage
  496. self.path = path
  497. }
  498. /// For maxSize API, return an error if the size is exceeded.
  499. private func checkSizeOverflow(task: StorageTask, maxSize: Int64) -> NSError? {
  500. if task.progress.totalUnitCount > maxSize || task.progress.completedUnitCount > maxSize {
  501. return StorageError.downloadSizeExceeded(
  502. total: task.progress.totalUnitCount,
  503. maxSize: maxSize
  504. ) as NSError
  505. }
  506. return nil
  507. }
  508. private func startAndObserveUploadTask(task: StorageUploadTask,
  509. completion: ((_: StorageMetadata?, _: Error?) -> Void)?) {
  510. if let completion {
  511. task.completionMetadata = completion
  512. let callbackQueue = storage.callbackQueue
  513. task.observe(.success) { snapshot in
  514. callbackQueue.async {
  515. task.completionMetadata?(snapshot.metadata, nil)
  516. task.completionMetadata = nil
  517. }
  518. }
  519. task.observe(.failure) { snapshot in
  520. callbackQueue.async {
  521. task.completionMetadata?(nil, snapshot.error)
  522. task.completionMetadata = nil
  523. }
  524. }
  525. }
  526. task.enqueue()
  527. }
  528. }