[英]How to retrieve nested nodes from Firebase realtime database to iOS app
I'm building a simple app which stores and retrieve data from firebase realtime database.我正在构建一个简单的应用程序,它可以从 firebase 实时数据库中存储和检索数据。 At present my database has these data of an user.
目前我的数据库有一个用户的这些数据。 Database content
数据库内容
Here is the code which I used to insert data.这是我用来插入数据的代码。
let ref = Database.database().reference()
let user = ref.child("bill")
user.setValue(["name":"Bill gates"])
user.child("Request/One").setValue(["Phno":" ","Message":" "])
As you can see I'm inserting a dictionary with empty values because I don't know how to create a child node without any data within them.如您所见,我正在插入一个包含空值的字典,因为我不知道如何创建一个没有任何数据的子节点。
I'm trying to retrieve the Request part of the database completely whenever a new node is added as a child to request node.每当将新节点作为子节点添加到请求节点时,我都会尝试完全检索数据库的请求部分。
Here I my code for retrieving这是我的检索代码
user.observe(.childAdded) { (DataSnapshot) in
for case let i as DataSnapshot in DataSnapshot.children
{
guard let dict = i.value as? [String:Any] else{print("Error"); return}
let a = dict["Message"] as? String
let b = dict["Phno"] as? String
print(a!)
print(b!)
}
}
But in above code it doesn't get called when I explicitly add a new node in database但是在上面的代码中,当我在数据库中明确添加一个新节点时它不会被调用
Solved it by using below code使用下面的代码解决了它
user.observe(.childAdded) { (DataSnapshot) in
if let dict = DataSnapshot.value as? NSDictionary
{
for i in dict.allKeys
{
if let data = dict[i] as? NSDictionary
{
let message = data["Message"] as! String
let phno = data["Phno"] as! String
if(message != "" && phno != "")
{
print(message)
print(phno)
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.