Search code examples
swiftfirebasefirebase-realtime-databasedata-retrieval

Firebase cannot get value from Dictionary


I am trying to retrieve users info from firebase.

rk70HDmNSGfugTcIbTdAKhKXE4K2 =     {
    Email = "johnny_bravo770@gmail.com";
    UserID = rk70HDmNSGfugTcIbTdAKhKXE4K2;
    Username = "Johnny_Bravo";
};

This is the snapshot I retrieve. I want to attain the users email but I get a crash due to a nil value

func retreiveUsers(){

    databaseRef.child("Users").observeSingleEvent(of: .value, with: { (snapshot) in

        if let fetchedUser = snapshot.value as? NSDictionary {

            print(fetchedUser["Email"])

        }
    })
}

What is Wrong?


Solution

  • It would be much better if you add more info. I have written in comment.

    But I think, that problem is that databaseRef.child("Users") will fetch all users node. You need to add .child(USER_ID) or do something like this:

    databaseRef.child("Users").observeSingleEvent(of: .value, with: { (snapshot) in
    
        for item in snapshot.children {
            let fetchedUserSnapshot = item as! FIRDataSnapshot
            if let fetchedUser = fetchedUserSnapshot.value as? [String: Any] {
                print(fetchedUser["Email"])
            }      
        }
    })
    

    Try this

    Hope it helps