【发布时间】:2017-10-27 00:15:06
【问题描述】:
我有以下 firebase 结构。Firebase Structure
“Users”是根,键是“Uid”。如何访问给定“Uid”的键的特定值?
示例:我想检索“Uid”为 M5j80aAlmCS3Jcbh0aA3T4Tfzxv1 的特定用户的“mobileno”。
【问题讨论】:
标签: ios swift firebase firebase-realtime-database
我有以下 firebase 结构。Firebase Structure
“Users”是根,键是“Uid”。如何访问给定“Uid”的键的特定值?
示例:我想检索“Uid”为 M5j80aAlmCS3Jcbh0aA3T4Tfzxv1 的特定用户的“mobileno”。
【问题讨论】:
标签: ios swift firebase firebase-realtime-database
要获取用户的个人资料信息,请使用 FIRUser 实例的属性。例如:
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
// ...
}
有关更多信息,请参阅Firebase Documentation。
【讨论】:
如果是您的(或用户的)uid:
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
}
}
})
}
您可以将变量 userUID 替换为 firebase 引用调用中的任何字符串值,它将获取该用户 - 我建议(如果您尝试从您的应用程序访问这些用户)填充 tableView 或 collectionView(某种类型列表)与所有用户。您还可以获取所有用户并遍历您想要的用户(假设您有一个布尔变量来显示该用户)。
【讨论】:
看看下面的代码,我使用了 Observe Block,因为我每次在聊天 App 中更新时都需要获取数据。所以你可以利用观察单个事件来获取数据,最后也可以移除观察者。
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
}
}
})
【讨论】: