StorageListTask.swift 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. /// A Task that lists the entries under a StorageReference
  16. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  17. enum StorageListTask {
  18. static func listTask(reference: StorageReference,
  19. queue: DispatchQueue,
  20. pageSize: Int64?,
  21. previousPageToken: String?,
  22. completion: ((_: StorageListResult?, _: Error?) -> Void)?) {
  23. var queryParams = [String: String]()
  24. let prefix = reference.fullPath
  25. if prefix.count > 0 {
  26. queryParams["prefix"] = "\(prefix)/"
  27. }
  28. // Firebase Storage uses file system semantics and treats slashes as separators. GCS's List
  29. // API
  30. // does not prescribe a separator, and hence we need to provide a slash as the delimiter.
  31. queryParams["delimiter"] = "/"
  32. // listAll() doesn't set a pageSize as this allows Firebase Storage to determine how many
  33. // items
  34. // to return per page. This removes the need to backfill results if Firebase Storage filters
  35. // objects that are considered invalid (such as items with two consecutive slashes).
  36. if let pageSize {
  37. queryParams["maxResults"] = "\(pageSize)"
  38. }
  39. if let previousPageToken {
  40. queryParams["pageToken"] = previousPageToken
  41. }
  42. let root = reference.root()
  43. let request = StorageUtils.defaultRequestForReference(
  44. reference: root,
  45. queryParams: queryParams
  46. )
  47. StorageInternalTask(reference: reference,
  48. queue: queue,
  49. request: request,
  50. httpMethod: "GET",
  51. fetcherComment: "ListTask") { (data: Data?, error: Error?) in
  52. if let error {
  53. completion?(nil, error)
  54. } else {
  55. if let data,
  56. let responseDictionary = try? JSONSerialization
  57. .jsonObject(with: data) as? [String: AnyHashable] {
  58. let listResult = StorageListResult(with: responseDictionary, reference: reference)
  59. completion?(listResult, nil)
  60. } else {
  61. completion?(nil, StorageErrorCode.error(withInvalidRequest: data))
  62. }
  63. }
  64. }
  65. }
  66. }