Gil Gil - 5 months ago 26
iOS Question

Firebase - how to get the key value in observeEventType = Value

This is a follow up question to Firebase - proper way to structure the DB




I have the following DB structure:

"artists" : {
"-KKMkpA22PeoHtBAPyKm" : {
"name" : "Skillet"
}
}


And i want to query the artists ref and see if an artist is already in the DB or not and if the artist IS in the DB, get the artist key (in the above example it would be -KKMkpA22PeoHtBAPyKm).

I tried this:

artistsRef.queryOrderedByChild("name").queryEqualToValue("Skillet").observeEventType(.Value, withBlock: { (snapshot) in
if snapshot.exists() {
print("we have that artist, the id is \(snapshot.key)")
} else {
print("we don't have that, add it to the DB now")
}
})


but "snapshot.key" only gives me the parent key which is "artists".

How can i get the key I need?

Answer

In if condition, you need to get allKeys to get "-KKMkpA22PeoHtBAPyKm" ...

    if snapshot.exists() {
        for a in snapshot.value.allKeys(){
            print(a)
        }
    } else {
        print("we don't have that, add it to the DB now")
    }
Comments