StorageReference.swift 26 KB

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