1
votes

I am new to swift and firebase, and I am wondering why I receive snapshot.value as? NSDictionary as nil even though the user is signed in.

 let uid = Auth.auth().currentUser?.uid
        
        Database.database().reference().child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
            print(snapshot.value as? NSDictionary)
            if let value = snapshot.value as? NSDictionary{
                self.title = value["firstname"] as? String
                print("o")
            }
            print(self.title)
            
        }, withCancel: { (error) in
            print(error.localizedDescription)
        })
    }
//I want it to return the name of the user (Ben) as the title of the navigation bar, but instead it returns nil

Database is:

    {
  "users" : {
    "-MBzED86cdVbvBNcYdpY" : {
      "email" : "[email protected]",
      "firstname" : "benjamin",
      "username" : "bb"
    },
    "-MBzEWEQ3cX6d5aJOByR" : {
      "email" : "[email protected]",
      "firstname" : "bslou",
      "username" : "bbbslou.row"
    }
}
}

My program returns "Snap (mDNGl4fQXEMx1wPnjGuhILp5f8j1) " when I print snapshot

1
What does print(type(of: snapshot.value)) show? And avoid to use NS... collection types in Swift.vadian
It shows FIRDataSnapshot, ok I will change to DictionaryBenjamin Sloutsky
Please edit the question to show the data that you expect this query to return. Since we can't see the contents of the database, and the specific value of uid, there's not much we can do. The result of the query is simply telling you that there's no data at the location you queried.Doug Stevenson
I edited the question @DougStevenson, I showed database tooBenjamin Sloutsky
When I print snapshot, I only get the idBenjamin Sloutsky

1 Answers

1
votes

The child keys in your database under "users" are not Firebase Auth user IDs. They look like randomly generated push IDs (aka "auto id"). Your query that uses UID is simply not going to find these children. Notice that the ID of your snapshot does not match the database at all. The snaphshot it empty - it contains no data.

You're going to have to go back to your code that creates these children and use the actual UID of the user, instead of using an auto ID.