[英]Swift Get Specific Value From Firebase Database
I'm trying to get a specific value from Firebase Database. 我正在尝试从Firebase数据库中获取特定值。 I looked some of the documents such as Google's, but I couldn't do it. 我看了一些像谷歌这样的文件,但我做不到。 Here is the JSON file of the database: 这是数据库的JSON文件:
{
"Kullanıcı" : {
"ahmetozrahat25" : {
"E-Mail" : "ahmetozrahat25@gmail.com",
"Yetki" : "user"
},
"banuozrht" : {
"E-Mail" : "banuozrahat@gmail.com",
"Yetki" : "user"
}
}
}
Swift Code: SWIFT代码:
ref?.child("Kullanıcı").child(userName.text!).observeSingleEvent(of: .value, with: { (snapshot) in
if let item = snapshot.value as? String{
self.changedName = item
}
})
I want to get E-Mail
value of a user, not everybody's. 我想获得用户E-Mail
价值,而不是每个人。 How can I do that? 我怎样才能做到这一点?
At last I found a solution. 最后我找到了解决方案。 If I declare a var and try to use later it returns nil, but if I try use snapshot.value as? String
如果我声明一个var并尝试稍后使用它会返回nil,但是如果我尝试使用snapshot.value as? String
snapshot.value as? String
it's ok. snapshot.value as? String
没关系。 Here is a example I did. 这是我做的一个例子。
ref: FIRDatabaseReference?
handle: FIRDatabaseHandle?
let user = FIRAuth.auth()?.currentUser
ref = FIRDatabase.database().reference()
handle = ref?.child("Kullanıcı").child((user?.uid)!).child("Yetki").observe(.value, with: { (snapshot) in
if let value = snapshot.value as? String{
if snapshot.value as? String == "admin"{
self.items.append("Soru Gönder")
self.self.tblView.reloadData()
}
}
})
In your code, the snapshot will contain a dictionary of child values. 在您的代码中,快照将包含子值的字典。 To access them, cast the snapshot.value as a Dictionary and then accessing the individual children is a snap (shot, lol) 要访问它们,请将snapshot.value转换为Dictionary,然后访问各个子项是一个快照(镜头,哈哈)
ref?.child("Kullanıcı").child(userName.text!)
.observeSingleEvent(of: .value, with: { (snapshot) in
let userDict = snapshot.value as! [String: Any]
let email = userDict["E-Mail"] as! String
let yetki = userDict["Yetki"] as! String
print("email: \(email) yetki: \(yetki)")
})
Add the "E-Mail" child to the query. 将“电子邮件”子项添加到查询中。
ref?.child("Kullanıcı").child(userName.text!).child("E-Mail").observeSingleEvent(of: .value, with: { (snapshot) in
if let item = snapshot.value as? String{
self.changedName = item
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.