如何解析firebase FDataSnapshot对象?

时间:2014-08-04 04:09:17

标签: ios objective-c swift firebase

我的代码从firebase检索结构化数据,但我不清楚如何从firebase数据对象中获取每个值。我没有在stackoverflow上找到答案,我发布了问题&回答其他初学者。

我的firebase快照对象值:

{
    "08AD8779-6EEB-4449-BC77-78A661ADA72E" =     {
        field1 = "to device id";
        field2 = "text message";
    };
    "EB841471-618C-4C52-8AA0-C20AD2C947AC" =     {
        field1 = "to device id";
        field2 = "text message";
    };
} 

如何将设备ID(例如“08AD8779-6EEB-4449-BC77-78A661ADA72E”)和'field1'和'field2'的值分配给NSString变量?

3 个答案:

答案 0 :(得分:7)

以下代码对我有用:

-(void)readFirebaseData {
    // Read data and react to changes
    [self.myRootRef observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {

        for (FDataSnapshot* childSnap in snapshot.children) {
            NSString* otherDeviceName = childSnap.name;
            NSLog(@"otherDeviceName -> %@", childSnap.name);
            NSLog(@"otherDeviceField1 -> %@", childSnap.value[@"field1"]);
            NSLog(@"otherDeviceField2 -> %@", childSnap.value[@"field2"]);
        }     
    }];
}

答案 1 :(得分:0)

希望这会有所帮助。在FDataSnashot上没有名称属性,因此将其视为具有键名的值。

        for childSnap in  snapshot.children.allObjects as [FDataSnapshot]{
            let otherDeviceName = childSnap.value["name"] as NSString
            println("otherDeviceName -> \(otherDeviceName)");
            let field1 = childSnap.value["field1"]
            let field2 = childSnap.value["field2"]
            println("otherDeviceField1 -> \(field1)");
            println("otherDeviceField2 -> \(field2)");
        }

答案 2 :(得分:0)

其他答案还可以,但是如果有人想要一个带有错误识别的干净结构:SnapshotParser

以下代码对于获得完全正常的快速表示是必要的:

func main(){
    let devices=SnapshotParser().parseAsList(snap: Snapshot, type: Device.self)
}

class Device: ParsableSnapshot {
    var id: String?
    var field1:String?=nil
    var field2:String?=nil

    required init(){}

    func bindProperties(binder: SnapshotParser.Binder) {
        binder.bindField(name: "id", field: &id)
        binder.bindField(name: "field1", field: &field1)
        binder.bindField(name: "field2", field: &field2)
    }
}