问题
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:
Here is my function:
Here is the output in the console:
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?
回答1:
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)")
}
}
})
回答2:
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.
回答3:
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)
}
}
来源:https://stackoverflow.com/questions/40200217/how-to-set-variables-from-a-firebase-snapshot-swift