如何解析Firebase实时数据库?
到目前为止,我的代码是:
var ref: DatabaseReference!
ref = Database.database().reference()
ref.child("data").observe(.childAdded) { (snapshot) in
print("snapshot = \(snapshot)")
}
我无法输入条件。
print("url = \(ref.url)")
url = "https://gdenamaz.firebaseio.com"
这个变种也不起作用
var ref: DatabaseReference!
ref = Database.database().reference().child("data")
ref.observeSingleEvent(of: .value) { (snapshot) in
for data in snapshot.children {
print("data = \(data)")
}
}
最佳答案
要引用官方文档-
refHandle = postRef.observe(DataEventType.value, with: { (snapshot) in
let postDict = snapshot.value as? [String : AnyObject] ?? [:]
// ...
})
您要查找的是
snapshot.value
而不是snapshot.children
另一个例子
let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let username = value?["username"] as? String ?? ""
let user = User(username: username)
// ...
}) { (error) in
print(error.localizedDescription)
}
同样,
.childAdded
仅在添加子项时触发。 IE,直到您真正更改了该节点引用中的任何内容,都不会发生任何事情。关于ios - 如何解析Firebase实时数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47713087/