DatabaseReference+WriteEncodable.swift 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * Copyright 2020 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import FirebaseDatabase
  18. extension DatabaseReference {
  19. /// Encodes an instance of `Encodable` and overwrites the encoded data
  20. /// to the path referred by this `DatabaseReference`. If no value exists,
  21. /// it is created. If a value already exists, it is overwritten.
  22. ///
  23. /// See `Database.Encoder` for more details about the encoding process.
  24. ///
  25. /// - Parameters:
  26. /// - value: An instance of `Encodable` to be encoded to a document.
  27. /// - encoder: An encoder instance to use to run the encoding.
  28. /// - completion: A block to execute once the value has been successfully
  29. /// written to the server. This block will not be called while
  30. /// the client is offline, though local changes will be visible
  31. /// immediately.
  32. public func setValue<T: Encodable>(from value: T,
  33. encoder: Database.Encoder = Database.Encoder(),
  34. completion: ((Error?) -> Void)? =
  35. nil) throws {
  36. let encoded = try encoder.encode(value)
  37. if let completion = completion {
  38. setValue(encoded, withCompletionBlock: { error, _ in completion(error) })
  39. } else {
  40. setValue(encoded)
  41. }
  42. }
  43. }