StorageUpdateMetadataTask.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. #if COCOAPODS
  16. import GTMSessionFetcher
  17. #else
  18. import GTMSessionFetcherCore
  19. #endif
  20. /// A Task that lists the entries under a StorageReference
  21. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  22. enum StorageUpdateMetadataTask {
  23. static func updateMetadataTask(reference: StorageReference,
  24. fetcherService: GTMSessionFetcherService,
  25. queue: DispatchQueue,
  26. metadata: StorageMetadata,
  27. completion: ((_: StorageMetadata?, _: Error?) -> Void)?) {
  28. var request = StorageUtils.defaultRequestForReference(reference: reference)
  29. let updateData = try? JSONSerialization.data(withJSONObject: metadata.updatedMetadata())
  30. request.httpBody = updateData
  31. request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
  32. if let count = updateData?.count {
  33. request.setValue("\(count)", forHTTPHeaderField: "Content-Length")
  34. }
  35. StorageInternalTask(reference: reference,
  36. fetcherService: fetcherService,
  37. queue: queue,
  38. request: request,
  39. httpMethod: "PATCH",
  40. fetcherComment: "GetMetadataTask") { (data: Data?, error: Error?) in
  41. if let error {
  42. completion?(nil, error)
  43. } else {
  44. if let data,
  45. let responseDictionary = try? JSONSerialization
  46. .jsonObject(with: data) as? [String: AnyHashable] {
  47. let metadata = StorageMetadata(dictionary: responseDictionary)
  48. metadata.fileType = .file
  49. completion?(metadata, nil)
  50. } else {
  51. completion?(nil, StorageErrorCode.error(withInvalidRequest: data))
  52. }
  53. }
  54. }
  55. }
  56. }