How to parse an FDataSnapshot firebase object?

my code is extracting structured data from firebase, but I did not understand how to get each value from the firebase data object. I did not find an answer on stackoverflow, I post a question and answer here for other newbies.

value of firebase snapshot object:

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

How to assign a device identifier (for example, "08AD8779-6EEB-4449-BC77-78A661ADA72E") and the value "field1" and "field2" to NSString variables?

+6
source share
3 answers

Below is the code that worked for me:

 -(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"]); } }]; } 
+7
source

Hope this helps. The FDataSnashot property has no name, so it is considered a value with the key name.

  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)"); } 
0
source

Other answers are fine, but if someone wants to have a clean structure with error recognition: SnapshotParser

To get a complete working quick view, you need the following code:

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

Source: https://habr.com/ru/post/973299/


All Articles