0

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

  • 1
    do like this https://stackoverflow.com/a/37759787/9137841 –  May 04 '21 at 05:12
  • Hi I solved that problem but now I'm facing new problem any idea how to solve this https://stackoverflow.com/questions/67385898/observer-not-calling-in-swift-ios-firebase-realtime-database – RetroModernGamer May 04 '21 at 13:46
  • Be careful here; first you cannot insert data with empty values - and there is not reason to even do that. In Firebase, nodes cannot be nil and any node that IS nil cannot exist. Second thing, and SUPER important this `"Phno":" "` is NOT an empty value. It's a space, which is a value. – Jay May 04 '21 at 20:02

1 Answers1

0

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)
            }
        
    }
   }
    
}
  • This answer is going to lead to a lot of grief. Please protect your code by safely unwrapping optionals. For example this `let message = data["Message"] as! String` will crash your app if the Message node is not found, at least use a coalescing operator to give it a default value `let message = data["Message"] as? String ?? "No Message"` – Jay May 04 '21 at 20:04