Hussain Mustafa
Hussain Mustafa

Reputation: 107

Firebase cannot get value from Dictionary

I am trying to retrieve users info from firebase.

rk70HDmNSGfugTcIbTdAKhKXE4K2 =     {
    Email = "[email protected]";
    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?

Upvotes: 0

Views: 603

Answers (1)

Vlad Pulichev
Vlad Pulichev

Reputation: 3272

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

Upvotes: 1

Related Questions