如何在另一个firebase子项中检索子(数组)

时间:2016-11-11 11:03:26

标签: ios arrays swift firebase

我正在尝试从array打印firebase。实际上,如果我们在列表中点击药物(tableviewcontroller),它将显示其特定的剂量。我被困在检索剂量清单。这是我从firebase获取数据的代码。任何帮助表示赞赏。提前致谢。我的firebase结构如下所示.. firebase img

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

    })

2 个答案:

答案 0 :(得分:0)

您应该查看firebase文档https://firebase.google.com/docs/database/ios/read-and-write

但如果我理解你的想法,你可能有一个药物的模型类。因此,要检索您的数据,您应该为Swift 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发送到下一个视图

答案 1 :(得分: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()
    })
    }