2017-04-09 219 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.