我正在尝试从firebase数据库中检索数据,但是当我运行代码时它没有显示任何内容,但没有显示错误
我从Firebase手册获得了这段代码,顺便说一句,我很确定路径是正确的
let ref = FIRDatabase.database().reference()
ref.child("users").child("user").child(username).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let score = value?["score"] as? String ?? ""
print(score)
// ...
}) { (error) in
print(error.localizedDescription)
}
JSON
{
"users" : {
"user" : {
"e1410kokeZS8xv81J1RzhN4V2852" : {
"email" : "aaaa@gmail.com",
"score" : 0,
"username" : "Afnan"
},
"jPx8XJ3Q9AazDM7qIOhz02PBfh22" : {
"email" : "aaaa@ggg.com",
"score" : 13,
"username" : "ghhh"
}
}
}
}
答案 0 :(得分:4)
您正在侦听.value
事件,但您的区块一次只处理一个项目,因此请使用.childAdded
事件。
let ref = FIRDatabase.database().reference().child("users").child("user").child(username)
ref.observeSingleEvent(of: .childAdded, with: { (snapshot) in
if let userDict = snapshot.value as? [String:Any] {
//Do not cast print it directly may be score is Int not string
print(userDict["score"])
}
}
注意:在Swift中使用原生Dictionary
代替NSDictionary