2016-11-11 54 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() 
    }) 
    } 
    
相关问题