Dustin Spengler Dustin Spengler - 6 months ago 35
Swift Question

Retrieve auto ID from FireBase JSON swift

I am uploading names to a table in FireBase using a loop which adds them using the

childByAutoID()
method like this:

for dependent in dependentsArray
{
let dependentName = dependent.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

CURRENT_USER_DEPENDENTS_URL.childByAutoId().setValue(["name" : dependentName])
}


which then looks like this in my dashboard:

enter image description here

I then observe the dependent table like so:

CURRENT_USER_DEPENDENTS_URL.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
self.dependentsJSON = snapshot.value as? [String : [String : String]]

}, withCancelBlock: { error in
print(error.description)
})


The
print
statement in the code above produces this JSON dictionary:

{
"-KH3Cg0KFvMNEULYUezv" = {
name = one;
};
"-KH3Cg0LeTs54nbYonmv" = {
name = two;
};
"-KH3Cg0LeTs54nbYonmw" = {
name = three;
};
"-KH3Cg0LeTs54nbYonmx" = {
name = four;
};
}


Very simply put I would like to be able to obtain the UIDs of each dependent from this JSON dictionary so i can then create an array of dependent UIDs in
NSUserDefaults
as well as sort the JSON dictionary like this:

if let firstName = self.dependentsJSON?["-KH3Cg0LeTs54nbYonmx"]?["name"] {
print(firstName)
}


Side note:
I can save the UIDs at the time when they are created and added to the database but the fact is the UIDs need to be obtained at run time incase a user ever uninstalls the app.

Answer

You can do the following

var idList = [String]()

CURRENT_USER_DEPENDENTS_URL.observeEventType(.Value, withBlock: { snapshot in
    //print(snapshot.value)
    self.dependentsJSON = snapshot.value as? [String : [String : String]]

    for dependent in self.dependentsJSON{
         idList.append(dependent.key)
    }

    }, withCancelBlock: { error in
        print(error.description)
})

Then you would access the values

if let firstName = self.dependentsJSON?[idList[0]]?["name"] {
    print(firstName)
}
Comments