Ryan Cocuzzo
Ryan Cocuzzo

Reputation: 3219

Accessing values from Children Firebase

I am really not quite understanding the updates to the Swift 3.0 Firebase syntax, but most of all retrieving values from children of a snapshot seems to be impossible. To do so, I use a snippet like this:

 if let snapVal = snapshot.value as? [String: AnyObject] {
     for c in snapshot.children {
                        let cx = (c as! AnyObject)
                        let name = cx["NAME"] as! String

     }
}

I have taken many approaches to this but FIRDatabaseSnapshot has many restrictions in the new Swift 3 update, and AnyObject does not allow for values to be read from the object and NSDictionary-like types do not have children either. All help is very appreciated, thank you!

Upvotes: 0

Views: 936

Answers (1)

Dravidian
Dravidian

Reputation: 9945

The snapShot that you receive of type FIRDataSnapshot is actually a custom class conforming to NSObject, so only the variables conforming to FIRDataSnapshot can access the custom function that FIRDataSnapshot provides such as .children.

But when you are accessing a new variable whose value is snap.value parsed as [String:AnyObject], basically it becomes a NSDictionary, and NSDictionary doesn't has any parameter .children.

  FIRDatabase.database().reference().child("your_Ref").observeSingleEvent(of: .value, with: {(snap) in

        for each in snap.children{

            print(each)


        }
      if let snapDict = snap.value as? [String:AnyObject]{

            for each in snapDict{

                let keyID = each.key
                let childValue = each.value["NAME"] as! String
            }
        }

    })

Upvotes: 2

Related Questions