1
votes

How I could send in correct way object with his own properties to the data base ?

Let's say object with properties :

class Test {
 var name:String
 var age:Int

 init(name: String, age: Int) {
  self.name = name
  self.age = age
 }
}

(...)
let obj = Test(name: "Jack", age: 25)
let databaseRef = FIRDatabase.database().reference().child("Person")

databaseRef.setValue(obj)

Data base should looks like this :

enter image description here

Whenever I add new person I'll get new child as a "person" parent.

Thanks in advance!

1

1 Answers

3
votes

For that, first you need to generate the unique personId using childByAutoId() and then add the person details to it.

let newPersonRef = FIRDatabase.database().reference().child("Person").childByAutoId()
let obj = Test(name: "Jack", age: 25)
newPersonRef.setValue(obj.toDictionary())

If you also want that newly created person's unique reference id:

let newPersonRef = FIRDatabase.database().reference().child("Person").childByAutoId()
print(newPersonRef.key)

Edit: Add one function with return type Any inside your Test class.

func toDictionary() -> Any {
    return ["name":name, "age": age] as Any
}

And then set the test object in Firebase this way:

let obj = Test(name: "Jack", age: 25)
newPersonRef.setValue(obj.toDictionary())