StorageUpdateMetadataTask.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 StorageUpdateMetadataTask {
  18. static func updateMetadataTask(reference: StorageReference,
  19. queue: DispatchQueue,
  20. metadata: StorageMetadata,
  21. completion: ((_: StorageMetadata?, _: Error?) -> Void)?) {
  22. var request = StorageUtils.defaultRequestForReference(reference: reference)
  23. let updateData = try? JSONSerialization.data(withJSONObject: metadata.updatedMetadata())
  24. request.httpBody = updateData
  25. request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
  26. if let count = updateData?.count {
  27. request.setValue("\(count)", forHTTPHeaderField: "Content-Length")
  28. }
  29. StorageInternalTask(reference: reference,
  30. queue: queue,
  31. request: request,
  32. httpMethod: "PATCH",
  33. fetcherComment: "GetMetadataTask") { (data: Data?, error: Error?) in
  34. if let error {
  35. completion?(nil, error)
  36. } else {
  37. if let data,
  38. let responseDictionary = try? JSONSerialization
  39. .jsonObject(with: data) as? [String: AnyHashable] {
  40. let metadata = StorageMetadata(dictionary: responseDictionary)
  41. metadata.fileType = .file
  42. completion?(metadata, nil)
  43. } else {
  44. completion?(nil, StorageErrorCode.error(withInvalidRequest: data))
  45. }
  46. }
  47. }
  48. }
  49. }