2016-11-11 53 views
0

我試圖從firebase打印array。實際上,如果我們點擊列表中的藥物(tableviewcontroller),它會顯示其特定劑量。我被困住以檢索劑量列表。這裏是我的代碼從firebase獲取數據。任何幫助表示讚賞。提前致謝。我的火力結構看起來像這樣.. firebase img如何檢索另一個Firebase子項中的子項(陣列)

func loadDataFromFirebase() { 


    databaseRef = FIRDatabase.database().reference().child("medication") 


    databaseRef.observeEventType(.Value, withBlock: { snapshot in 


     for item in snapshot.children{ 
     FIRDatabase.database().reference().child("medication").child("options").observeEventType(.Value, withBlock: {snapshot in 
       print(snapshot.value) 
      }) 
     } 

    }) 

回答

0

你應該採取火力文檔https://firebase.google.com/docs/database/ios/read-and-write

看看,但如果我理解你的想法,你可能對你的藥物模型類。因此,要檢索數據,你應該爲雨燕3.0這樣做:

func loadDataFromFirebase() { 


databaseRef = FIRDatabase.database().reference().child("medication") 


databaseRef.observe(.value, with: { (snapshot) in 

    for item in snapshot.children{ 
    // here you have the objects that contains your medications 
    let value = item.value as? NSDictionary 

    let name = value?["name"] as? String ?? "" 
    let dossage = value?["dossage"] as? String ?? "" 
    let type = value?["type"] as? String ?? "" 
    let options = value?["options"] as? [String] ?? "" 

    let medication = Medication(name: name, dossage: dossage, type: type, options: options) 
    // now you populate your medications array 
    yourArrayOfMedications.append(medication) 
    } 

    yourTableView.reloadData() 
}) 
} 

現在,你有你的陣列,所有的藥物,你只需要使用此藥物來填充您的tableView。當有人按上表中的項目,你可以叫prepareForSegue:併發送yourArrayOfMedications[indexPath.row].options下一個視圖

+0

請SWIFT 2.2 .. – tecE

+0

我想打印在一個單獨的表視圖「選項」,如果我們選擇它的藥物名稱。問題是,在數組.. ..檢索它作爲一個字符串顯示錯誤...在這裏拖長了.. – tecE

0
  • 的解決方案是與上面相同,但有小的變化。

    func loadDataFromFirebase() { 
        databaseRef = FIRDatabase.database().reference().child("medication") 
        databaseRef.observe(.value, with: { (snapshot) in 
    
        for item in snapshot.children{ 
        // here you have the objects that contains your medications 
        let value = item.value as? NSDictionary 
    
        let name = value?["name"] as? String ?? "" 
        let dossage = value?["dossage"] as? String ?? "" 
        let type = value?["type"] as? String ?? "" 
        let options = value?["options"] as? [String : String] ?? [:] 
    
        print(options["first"]) // -> this will print 100 as per your image 
        // Similarly you can add do whatever you want with this data 
    
        let medication = Medication(name: name, dossage: dossage, type: type, options: options) 
        // now you populate your medications array 
        yourArrayOfMedications.append(medication) 
    } 
    
    yourTableView.reloadData() 
    }) 
    } 
    
相關問題