LEVIS OGCPAS
LEVIS OGCPAS

Reputation: 229

Retrieving Child Node Data

I’m trying to recover the data on an specific child node. Here is the structure:

RESTAURANTS
    KTNfWKLD0isCsrpys
        name: “McDonalds”
        loc: “LA”
    KTNfWKLD0isCsrpys
        name: “KFC”
        loc: “LV”

Code:

FIRDatabase.database().reference().child("RESTAURANTS".observeSingleEventOfType(.ChildAdded, withBlock: { (snapshot) in

        for names in snapshot.children {
            self.loadingNames.append(names.key)
        }

    })

I tried this but I only get the children names like this [“name”,”loc"], but I want to get the names like this [“McDonalds”,”KFC”].

Upvotes: 0

Views: 94

Answers (2)

Bhavin Bhadani
Bhavin Bhadani

Reputation: 22374

Try something like this...

FIRDatabase.database().reference().child("RESTAURANTS".observeEventType(.ChildAdded, withBlock: { (snapshot) in

    if let name = snapshot.value?["name"] as? String {
        self.loadingNames.append(name)
    }
})

Edit: change observer observeSingleEventOfType to observeEventType

Upvotes: 1

ronatory
ronatory

Reputation: 7324

You can append the names to your string array like that:

FIRDatabase.database().reference().child("RESTAURANTS".observeSingleEventOfType(.ChildAdded, withBlock: { (snapshot) in
  for names in snapshot.children {
    if let name = names as? FIRDataSnapshot  {
      let nameValue = name.childSnapshot(forPath: "name").value as! String
      self.loadingNames.append(nameValue)
    }
  }  
})

Upvotes: 0

Related Questions