Reputation: 11
I have the following firebase structure.Firebase Structure
"Users" is the root, with the keys as "Uid". How do i access a particular value of a key for a given "Uid"?
Example: I want to retrieve "mobileno" of a particular user with "Uid" as M5j80aAlmCS3Jcbh0aA3T4Tfzxv1.
Upvotes: 1
Views: 1649
Reputation: 4855
Have a look at below code I had used Observe Block as I required to get data each time it was updated in a chat App . so you can make use of observe single event to get data and at end remove observer too.
Database.database().reference().child("users").child(your Key value).observe(.value, with: { (snapshot) in
if snapshot.exists(){
print(snapshot)
if let snapDict = snapshot.value as? [String:AnyObject] {
//here you can get data as string , int or anyway you want
self. mobilenoLabel.text = snapDict["mobileno"] as? String
}
}
})
Upvotes: 1
Reputation: 907
If it is your uid (or the user's):
if let userUID = Auth.auth().currentUser?.uid{
%firebaseReferenceVariable%.child("Users/\(userUID)").observeSingleEvent(of: .value, with: { snapshot in
if snapshot.value is NSNull{
//handles errors
return
}
else{
if let selectedUser = snapshot.value as? NSDictionary //OR [Stirng: Any]{
let mobileno = selectedUser["mobileno"] as! String
//Do something with mobileno
}
}
})
}
You can replace the variable userUID with any string value in the firebase reference call and it will get that user - I would recommend (if you are trying to access these users from your app) to populate a tableView or collectionView (some type of list) with all the users. You can also get all the users and loop through ones you want (let's saying if you had a boolean variable to display this user).
Upvotes: 1
Reputation: 1253
To get a user's profile information, use the properties of an instance of FIRUser. For example :
let user = Auth.auth().currentUser
if let user = user {
// The user's ID, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server,
// if you have one. Use getTokenWithCompletion:completion: instead.
let uid = user.uid
let email = user.email
let photoURL = user.photoURL
// ...
}
Refer to the Firebase Documentation for more info on this.
Upvotes: 2