Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 and Firebase: Retrieve auto id value from snapshot

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

enter image description here

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.

like image 644
Enzo Avatar asked Feb 03 '26 07:02

Enzo


1 Answers

.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)")
        } 
    })
like image 129
Jay Avatar answered Feb 06 '26 05:02

Jay