Aqeel iqbal Aqeel iqbal - 1 month ago 7
iOS Question

how to get the unique key that was created adding a child in firebase?

I am using firebase database for my ios project.

I added some fields using

childByAutoId
.

[[[_ref child:@"Users"] childByAutoId] setValue:@{@"data": @"my new json data string By aqeel", @"email": @"abc.xyz@email.com"}];


Now for some reason I have to search a specific child from database, say an email id. If email id exists I want to get that unique key of that child.

I am doing this

[[[[_ref child:@"Users"] queryOrderedByChild: @"email" ] queryEqualToValue:@"abc.xyz@email.com" ] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
NSLog(@"%@ Key %@ Value", snapshot.key,snapshot.value);
}];


Here in key I get "Users" and in value I get all the entries in
Users
field. But I want to get the key for the child
abc.xyz@email.com
.

Can someone provide me a sample code?

Answer

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

This means that you will have to loop over the snapshot.children.

Alternatively you can listen for a single .ChildAdded event and get the child that way:

[[[[_ref child:@"Users"] 
    queryOrderedByChild: @"email" ] 
    queryEqualToValue:@"abc.xyz@email.com" ] 
    observeSingleEventOfType:FIRDataEventTypeChildAdded withBlock:^(FIRDataSnapshot *snapshot) {
        NSLog(@"%@ Key %@ Value", snapshot.key,snapshot.value);
}];