I created the structure below on firebase and I need to get the auto id underlined in red:

The code I created to query the values:
let query = reference.queryOrdered(byChild: "receiverId").queryEqual(toValue: "LKupL7KYiedpr6uEizdCapezJ6i2")
//Start process
query.observe(.value, with: { (snapshot) in
guard snapshot.exists() else{
print("Data doesn't exists")
return
}
print(snapshot.key)
}
My "snapshot.value" results in:
Optional({
"-KaRVjQgfFD00GXurK9m" = {
receiverId = LKupL7KYiedpr6uEizdCapezJ6i2;
senderId = bS6JPkEDXIVrlYtSeQQgOjCNTii1;
timestamp = 1484389589738;
};
})
How do I get only the string -KaRVjQgfFD00GXurK9m from the node above?
I had tried using "print(snapshot.key)" but it results on the user ID: bS6JPkEDXIVrlYtSeQQgOjCNTii1
Some ideas? Thank you very much.
.value returns the parent node and all of the child nodes that satisfy the results of the query. In this case, the children would need to be iterated over (there could be more than 1 child that matches the query).
The snapshot.key is the parent node key (bS6JPkEDXIVrlYtSeQQgOjCNTii1) and the value is a snapshot (dictionary) of all of the children. Each of those children is a key:value pair of uid:value and value a dictionary of the child nodes, receiverId, senderId etc
This code will print the uid of each child node and one of the values, timestamp, for each user node that matches the query.
let usersRef = ref.child("users")
let queryRef = usersRef.queryOrdered(byChild: "receiverId")
.queryEqual(toValue: "LKupL7KYiedpr6uEizdCapezJ6i2")
queryRef.observeSingleEvent(of: .value, with: { (snapshot) in
for snap in snapshot.children {
let userSnap = snap as! FIRDataSnapshot
let uid = userSnap.key //the uid of each user
let userDict = userSnap.value as! [String:AnyObject]
let timestamp = userDict["timestamp"] as! String
print("key = \(uid) and timestamp = \(timestamp)")
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With