StorageReference.swift 27 KB

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