I'm having issue getting data from Firebase.
schema is
{
title: "dog",
images: {
main: "dog.png",
others: {
0: "1.png",
1: "2.png",
2: "3.png"
}
}
}
how can i parse FDataSnapshot to swift model??
Firebase is a NoSQL JSON database and has no schema and no tables. Data is stored with a 'tree' structure with nodes; parents and children.
You don't need to parse Firebase JSON data to access it, you can access it directly.
FDataSnapshots contain a .key, which is it's parent key in Firebase and .value. .Value may contain one node, or multiple nodes. The Value will have key:value pairs representing the data within the snapshot
So for your example you will have a Firebase structure like this
dogs
dog_id_0
title: "dog"
type: "Alaskan Malamute"
images:
main: "dog.png"
others:
0: "1.png"
1: "2.png"
dog_id_1
title: "another dog"
type: "Boxer"
images:
main: "another_dog.png"
others:
0: "3.png"
1: "4.png"
So, say you want to read in each dog_id_x node one at a time and print some values.
var ref = Firebase(url:"https://your-app.firebaseio.com/dogs")
ref.observeEventType(.ChildAdded, withBlock: { snapshot in
println(snapshot.value.objectForKey("title"))
println(snapshot.value.objectForKey("type"))
})
This will output
dog
Alaskan Malamute
another dog
Boxer
The dog_id_0 and dog_id_1 are node names created with the Firebase childByAutoId.
You could just as easily create a Dog class, and pass it the FDataSnapshot which will populate the class from the data within the snapshot.
February 2017 Update, Swift 3 Xcode 8
Since a lot of things with Swift3 and Firebase have changed by the time this question was asked I will provide an updated way to parse Firebase data:
let userID = FIRAuth.auth()?.currentUser?.uid
//I am registering to listen to a specific answer to appear
self.ref.child("queryResponse").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
//in my case the answer is of type array so I can cast it like this, should also work with NSDictionary or NSNumber
if let snapshotValue = snapshot.value as? NSArray{
//then I iterate over the values
for snapDict in snapshotValue{
//and I cast the objects to swift Dictionaries
let dict = snapDict as! Dictionary<String, Any>
}
}
}) { (error) in
print(error.localizedDescription)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With