如何从Firebase快照为子节点中的值分配变量?

时间:2017-04-13 23:40:35

标签: ios swift dictionary firebase firebase-realtime-database

我正在尽量减少向Firebase发出的数据请求数量。我有一个快照,可以提取以下数据:

snap (Hole1) {
GreenBackX = "40.196339";
GreenBackY = "-105.07354";
GreenCenterX = "40.196336";
GreenCenterY = "-105.073409";
GreenFrontX = "40.196342";
GreenFrontY = "-105.073283";
Hazard1 =     {
    CarryX = "40.196839";
    CarryY = "-105.07104";
    FrontX = "40.196893";
    FrontY = "-105.070626";
    Name = "R Fwy Bunker";
};
Hazard2 =     {
    CarryX = "40.196321";
    CarryY = "-105.071922";
    FrontX = "40.196383";
    FrontY = "-105.071573";
    Name = "L Fwy Bunker";
};
Hazard3 =     {
    CarryX = "40.196622";
    CarryY = "-105.072935";
    FrontX = "40.196662";
    FrontY = "-105.072554";
    Name = "R Fwy Bunker 2";
};
Hazard4 =     {
    CarryX = "40.196176";
    CarryY = "-105.073545";
    FrontX = "40.196225";
    FrontY = "-105.073167";
    Name = "L Greenside Bunker";
};
HoleH = "258.74";
HoleX = "40.19664";
HoleY = "-105.070484";
}

我的目标是分配一个Hazard1\Name的变量。到目前为止,我只是在文档中看到了如何获取初始值的工作示例,我喜欢这样:let holeX = value?["HoleX"] as? Double ?? 0,但我似乎无法找到任何让我这样做的东西第二级'如果你愿意的话。

有一个例子似乎说你可以通过这种方式引用它:let hazard1Name = value?["Hazard1/Name"]但我无法让它发挥作用。

1 个答案:

答案 0 :(得分:0)

FIRDataSnapshot包含来自给定Firebase数据库位置的数据。数据已经已下载,因此没有太多优化空间,抱歉: - (

我认为您可能正在寻找的是:

let ref: FIRDatabaseReference = ...
ref.child("Hazard1").child("Name").observeSingleEvent(of: .value) {
    (snapshot) in
    let name = snapshot.value as! String
    print("Name: \(name)")
}

否则,如果您只是想要从上述快照中获取数据,请尝试以下方法:

let snapshot: FIRDataSnapshot = ...
let data = snapshot.value as! [String: Any]
let hazard1 = data["Hazard1"] as! [String: Any]
let name = hazard1["Name"] as! String