0

This is my structure in the Firebase Realtime database:

enter image description here

I want to get for all products the name.

Here's what I tried:

database.child("customerID").child("productTopSeller").observe(FIRDataEventType.value, with: { (snapshot) in
  for childSnap in snapshot.children.allObjects {
    let product = childSnap as! FIRDataSnapshot
    print(product.value?["name"] as? String ?? "")
  }
}) { (error) in
  print(error.localizedDescription)
}

But this gives my following error:

Type 'Any' has no subscript members.

I know I would need to cast the snapshot somehow but couldn't figure out how to do this. using Swift 3.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Did you try googling the [error](http://stackoverflow.com/questions/39516199/type-any-has-no-subscript-members-in-xcode-8-swift-3)? – Rikh Apr 09 '17 at 19:02

1 Answers1

3

You need to cast product.value to [String:Any]. Look ad the following code

ref.child("customerID").child("productTopSeller").observeSingleEvent(of: .value, with: { snapshot in
  let names = snapshot
      .children
      .flatMap { $0 as? FIRDataSnapshot }
      .flatMap { $0.value as? [String:Any] }
      .flatMap { $0["name"] as? String }

  print(names)    
})

Please note I am using observeSingleEvent in order to get only one callback from Firebase. Your code does use observe instead which produce a callback every time the observed data does change.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148