我想在标签中显示某个 Firebase 子项数据的值。
我的代码如下:
let ref = FIRDatabase.database().reference()
ref.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in
let users = snapshot.value as! [String : AnyObject]
for (_, value) in users {
if let fullName = value["name"] as? String {
if let role = value["role"] as? String {
if let mtid = value["mtid"] as? Int {
let userNAME = fullName
let userROLE = role
let userMTID = mtid
print("ID: \(mtid) and NAME: \(fullName) and ROLE: \(role)")
self.mtidLabel.text = userMTID
self.roleLabel.text = userROLE
self.nameLabel.text = userNAME
}
}
}
}
})
我的数据库如下:
users:
- 1234567
* mtid: 1234567
* name: "John Smith"
* role: "coordinator"
- 2278433
* mtid: 2278433
* name: "John Doe"
* role: "developer"
- 2317894
* mtid: 2317894
* name: "Doe Smith"
* role: "crew"
本质上,如果用户在文本框中输入一串数字,例如 2317894,我希望它将 child 的 mtid 值显示为 2317894,名称为“Doe Smith”,角色为“crew”,所有这些都单独显示文本框。
当我使用上面的代码时,它仅选择要显示的选项之一并将所有选项打印到控制台。
有人知道我做错了什么吗?
最佳答案
我已经回答了我自己的问题。 我在代码中更改了以下内容
删除了用户中的for (_, value)
将 let users = snapshot.value 更改为! [String : AnyObject]
到 让 users = snapshot.value 作为! NSDictionary
在 ref.child("users")
和 .queryOrderedByKey()
之间添加了 .child(self.TEXTBOX_THAT_CONTAINS_CHILD_NUMBER_EG_1234567.text!)
最终代码:
ref.child("users").child(self.TEXTBOX_THAT_CONTAINS_CHILD_NUMBER_EG_1234567.text!).queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
let snapshotValue = snapshot.value as! NSDictionary
if let fullName = snapshotValue["name"] as? String {
if let role = snapshotValue["role"] as? String {
if let mtid = snapshotValue["mtid"] as? Int {
let userNAME = fullName
let userROLE = role
let userMTID = mtid
print("ID: \(mtid) and NAME: \(fullName) and ROLE: \(role)")
self.mtidLabel.text = userMTID
self.roleLabel.text = userROLE
self.nameLabel.text = userNAME
}
}
}
})
关于ios - 在标签中显示某个 firebase 子项的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44688865/