Swiftaccnt Swiftaccnt - 1 year ago 235
iOS Question

Friends list on Firebase

So far on my firebase I have something like:

username: Jill
username: Jack

I'm basically going to just have a text field and when someone hits the "add" button, a search through firebase gets done to make sure that username exists, and go from there on connecting the two as friends.

My question is I'm not understanding how I would sort through my data if it's structured like this? I might be totally missing something but is there a way to search through what I have now and say "Go to my users reference, go to through each UID and pull out the username and see if it matches what the user put in the text field, and if so grab the UID connected to the username"?

I'm almost thinking I need to have an entirely separate branch? that I have in addition to what I already have that looks like


Which would then allow me to just go to my usernames and go through and check through the values inside that (jack/Jill) and then if it exists then pull that uid out of the username.

1) Do I need both of these branches or is there a way to accomplish what I'm trying to do with just my first?

2) How exactly do I check for that match? Would a query be used or just checking for Null somehow?

3) Is this even the right way to go about doing this? I've found little to no information on friends lists online so this is just all an assumption.

Any help is appreciated!

Answer Source

Using the below structure, you can check if a user exists with a single query. Here's all the code you need:

This is the db structure:

   username: Jill
   username: Jack

Here is the code:

    var usernameEntered = self.usernameField.text!

    var databaseReferenceQuery = self.ref.child("users").queryOrderedByChild("username").queryEqualToValue(usernameEntered).observeSingleEventOfType(.Value, withBlock: { (snapshot) in

        if ( snapshot.value is NSNull ) {

            // No user :(

        } else {

           // User exists! Do stuff!


        }, withCancelBlock: { (error) in

           // An error occurred

Once you have established a user exists, I can think of a few ways to go about getting the uid. The key is to find a place where both the uid and the username are stored.

Option 1:

Create another branch in the users db structure that stores the uid. Set up this branch when the user is signed up.

Option 2:

Store the username as the displayName in the standard auth system and get the uid from there. Set this up when the user signs up.

That's up to you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download