pho_pho
pho_pho

Reputation: 734

Firebase: Accessing Data Stored via childByAutoID

So my Firebase data structure looks like this:

My JSON data structure

My question is simple. How do I access the ID's that have been stored via the childByAutoID method i.e. what is the key to their value. The reason I want to do this is because I want to create a variable that will hold the ID, and this only (the value generated by childByAutoId), for example, if you look at My JSON data structure image, KMVrGnR76E6vrj61K21 will be stored in the variable and this alone. My current query looks like this:

databaseRef.child("Jokes").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

            let jokeId = snapshot.//something??? not .key as this returns Jokes


        })

I understand that the childByAutoId generates a unique identifier, but surely there must be a way to retrieve and store that identifier (this alone, not all of it's children) for obvious reasons...

Upvotes: 1

Views: 740

Answers (3)

pho_pho
pho_pho

Reputation: 734

I have the answer. To access the key of the randomly generated autoId, you have to pass it as a FIRDataSnapShot.

for snap in snapshot.children.allObjects {

            let id = snap as! FIRDataSnapshot

            print(id.key)

        }

This will give you the randomly generated keys.

Upvotes: 2

Travis
Travis

Reputation: 2462

Within the for block, joke.key will be the id of the current child.

See FIRDataSnapshot

Upvotes: 0

rigdonmr
rigdonmr

Reputation: 2702

snapshot.key should get you the id for each joke in this case

Upvotes: 2

Related Questions