Ad

How To Retrieve The Middle Value Of A Node

I have a Firebase structure like this

"lists" : {
  "-LlBpKy9Q8UfCXCweM4b" : {
    "-LlBy-5Q9HX0YLFkBkev" : {
      "6416739414706" : {
        "addedDate" : "12-8-2019 at: 20:45:38",
        "amount" : 1,
        "contentSize" : 100,
        "objectProducer" : "Nailman",
        "objectType" : "Nails",
        "unit" : "Pcs"
      }
    }
  }
}

I would like to retrieve the objectID ( 6416739414706 ) I retrieve all other values like this:

ref?.observeSingleEvent(of: .value, with: { (snapshot) in
    for child in snapshot.children.allObjects as! [DataSnapshot] {
    // print(child.value)
    guard let dict = child.value as? [String: AnyObject] else { return }
    self.objectProducer.append(dict["objectProducer"] as! String)
    self.objectType.append(dict["objectType"] as! String)
    self.contentSize.append(dict["contentSize"] as! Double)
    self.objectMeasureUnit.append(dict["unit"] as! String)
    self.objectAmount.append(dict["amount"] as! Double)
    self.objectLastAdded.append(dict["addedDate"] as! String)     
}

This works fine, but I have not been able to retrieve the objectID. How can this be done?

Ad

Answer

The DataSnapshot class has a value property which you are retrieving and assigning to dict and a key property which in your case holds the objectID you are looking for.

So to get the objectIDString:

let objectID = child.key
Ad
source: stackoverflow.com
Ad