2017-04-09 248 views
0

一个孩子的所有键这是我在火力地堡实时数据库结构:迭代通过火力地堡

enter image description here

我想要得到的所有产品的名称。

这里是我的尝试:

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) 
} 

但是这给了我以下错误:

Type 'Any' has no subscript members. 

我知道我需要以某种方式投快照但无法弄清楚如何做到这一点。使用Swift 3.

+0

你尝试使用Google的[错误](http://stackoverflow.com/questions/39516199/type-any-has-no-subscript-members-in-xcode -8-迅速-3)? – Rikh

回答

2

您需要将product.value转换为[String:Any]。看广告下面的代码

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.