1
votes

I would like to grab the data from my Firebase snapshot and set it to variables in my Project. I get the data, but I don't know how to parse it so I can set them. I'm trying to do something like what SwiftyJSON does with API calls.

Here is my data structure in firebase: data structure

Here is my function: function

Here is the output in the console: output

Is there any way to parse and set values from the (ls) array and set the "fromId", "text", "toId" to different variables for each node?

3
Post you code as text not snippet - Dravidian
An important point to note is that the returned snapshot is not an array, it's a Dictionary so the order the data is not guaranteed (technically FIRDataSnapshot). You can use .orderBy to set the order with Firebase or sort it in code if ordering is important. The Firebase documentation covers how to parse the data in a Snapshot Read & Write Data. Although the docs are not currently very Swifty, apply the practice in @Dravidian answer. - Jay

3 Answers

2
votes

Try using:-

FIRDatabase.database().reference().child("users/userID/ls").observeSingleEvent(of : .value, with : {(Snap) in 

  if let snapDict = Snap.value as? [String:AnyObject]{

      for each in snapDict{

           print("\(each.value["fromId"] as! String)")

         }
   }
})
0
votes

You should be able to cast the FIRDataSnapshot value into a [String:Any] dictionary and then access the values using the "fromId", "text", and "toId" keys and assign those values to variables.

0
votes

The easy way would be: SnapshotParser

Just implement your classes:

func main(){
    let users=SnapshotParser().parseAsList(snap: Snapshot, type: User.self)
    for user in users{
        //do something with your object
    }
}

class User: ParsableSnapshot {
    var id:String?=nil
    var email:String?=nil
    var ls:[Ls]?=nil

    required init(){}

    func bindProperties(binder: SnapshotParser.Binder) {
        binder.bindField(name: "id", field: &id)
        binder.bindField(name: "email", field: &email)
        binder.bindList(name: "ls", list: &ls)
    }
}

class Ls: ParsableSnapshot {
    var id:String?=nil
    var fromId:String?=nil
    var text:String?=nil
    var told:String?=nil

    required init(){}

    func bindProperties(binder: SnapshotParser.Binder) {
        binder.bindField(name: "id", field: &id)
        binder.bindField(name: "fromId", field: &fromId)
        binder.bindField(name: "text", field: &text)
        binder.bindField(name: "told", field: &told)
    }
}