I'm building a simple app which stores and retrieve data from firebase realtime database. 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)
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.