Home > Net >  How to read values of a child from Firebase Realtime DB?
How to read values of a child from Firebase Realtime DB?

Time:11-25

I am trying to get values from my database. However, I am unsuccessful. Here is what the DB looks like:

enter image description here

Here is what I tried to do, to read the values:

    taskRef = Database.database().reference(withPath: "Tasks").child(titleOfTask)

    taskRef?.observeSingleEvent(of: .childAdded, with: { (snapshot) in
         if let taskDict = snapshot.value as? [String:Any] {
            print("Printing ---------> ",taskDict["Description"] as Any)
         }
    })

but nothing happens. Ideally, I want to read both the description in a different variable and due date into a different variable.


Important Things to know:

  • "Tasks" is.. you can think of it as a table name.
  • Alpha, Bravo, Jalabi... etc are all "Task Names" or childs of "Tasks"
  • Description, Due Date are the values

CodePudding user response:

You're attaching a listener to /Tasks/$titleOfTask in your JSON, say /Tasks/Alpha. That listener is asking to be called for the first child node of /Tasks/Alpha, so the snapshot in your code will point to /Tasks/Alpha/Description. When you then print taskDict["Description"], you are printing the value of /Tasks/Alpha/Description/Description, which does not exist.

The simplest fix is to listen for the .value event:

taskRef?.observeSingleEvent(of: .value, with: { (snapshot) in
     if let taskDict = snapshot.value as? [String:Any] {
        print("Printing ---------> ",taskDict["Description"] as Any)
     }
})

Now the snapshot has all data from /Tasks/Alpha, and thus the taskDict["Description"] ends up being the value from /Tasks/Alpha/Description.

  • Related