Retrieving Data using Firebase Swift

I’m using Firebase for my Swift iOS application. I found the retrieving data tutorial on Firebase’s guide a bit confusing and I am not sure why when I try to access existing values in my database results in nil values.

This is what I have so far:

  • Get data out of array of Firebase snapshots
  • Using Firebase observeSingleEventOfType synchronously
  • How to send actionable notifications to iOS with FireBase?
  • Reading Firebase Auth Error Thrown (Firebase 3.x and Swift)
  • Firebase pending dynamic links not working
  • Pagination while scrolling in Swift Firebase
  • usersRef.queryOrderedByChild("fbid").queryEqualToValue(userId).observeSingleEventOfType(.Value, withBlock:{ snapshot in
                            print("SNAPSHOT: ",snapshot.value)
    

    Here is the result of printing snapshot.

    SNAPSHOT:  {
        1 = {
            fbid = 1;
            firstName = Michelle;
            friendlist =         {
                9 = "Kevin C";
            };
            lastName = C;
            profilepicurl = "https:;
            uid = "facebook:1";
        };
    }
    

    However, the line below results in:
    fatal error: unexpectedly found nil while unwrapping an Optional value

     firstName = snapshot.value.objectForKey("firstName") as! String
    

    I would like to retrieve all the values for the user (firstName, profilepicurl, friendlist, etc) and store them in variables. It seems simple but perhaps I’m missing something. Any help would be appreciated.

    Solutions Collect From Internet About “Retrieving Data using Firebase Swift”

    Your FDataSnapshot does not contain a child firstName. It only contains a child 1.

    This is because you’re performing a query and then asking for a value. Since a query can have many results, it returns a list of results. Even when there’s only one result, it is still a list of 1.

    The solution is to loop over the children:

    usersRef.queryOrderedByChild("fbid")
            .queryEqualToValue(userId)
            .observeSingleEventOfType(.Value, withBlock:{ snapshot in
                for child in snapshot.children {
                    print("Loading group \(child.key!)") 
                }
    })