Reputation: 4519
I have some problems when I add a new node to the Firebase Realtime Database. I get some data back when I add a child, but the problem is that I retrieve the key and 1 value, but there are 2 values total.
I have the following structure:
-- groups
-- id
-- members
-- id
--device_name
--device_type
I observe the members child. And I want to retrieve the id and underlaying elements (device_name, device_type) when that child is added.
I do that with this code:
let ref = Database.database().reference().child("groups").child(roomObject.getAutoChildId()).child("members");
ref.observe(.childAdded, with: { (snapshot) in
print(snapshot.debugDescription)
})
But now the problem. snapshot.debugDescription returns not all the values in that snapshot. Example:
Snap (ooDpijaPrKgcBA70LUXYbpohvi42) {
"device_name" = test;
}
The device_type key is not there, and I don't know why. I need this:
Snap (ooDpijaPrKgcBA70LUXYbpohvi42) {
"device_name" = test;
"device_type" = test;
}
Added the structure:
Upvotes: 0
Views: 101
Reputation: 4519
I have found what was going wrong. It has nothing to do with the .childAdded, that part is working fine.
It goes wrong at the insert. What I did was the following:
let insertRef = reference.child("groups").child(roomKey).child("members").child(roomCodeArray[1])
insertRef.child("device_name").setValue(roomCodeArray[2])
insertRef.child("device_type").setValue(roomCodeArray[3])
But firebase is so freakin fast that when device_name is inserted, the other device retrieves the onchildChanged event. The device type is not added at that moment.
My solution:
let childInsert = [
"device_name" : roomCodeArray[2],
"device_type" : roomCodeArray[3]
]
insertRef.setValue(childInsert)
Insert the values at the same time. And then it works like magic.
Upvotes: 2