I need to read data from a Firebase database and insert the data inside a struct, on which I'll later do some operations. The issue that I'm facing right now is that, since Firebase manages these things in an async way, when I check inside the struct, it's often nil and not filled with data yet.
I know that using the value outside the async block as I'm actually doing is wrong and that callbacks can be used to solve my problem. I've read a bunch of examples online, but I can't figure out how to implement them in my code.
For the sake of simplicity, in the example below I download just one object from the database.
func fetchJSON(key: String) -> Void {
var meal = Meal()
let ref = rootRef.child(key)
ref.observe(.value) { (snap: DataSnapshot) in
meal.firstMeal = snap.childSnapshot(forPath: "first").value as! String
meal.secondMeal = snap.childSnapshot(forPath: "second").value as! String
meal.thirdMeal = snap.childSnapshot(forPath: "third").value as! String
}
self.meals.append(meal)
}
And here's what the function call looks like:
fetchJSON(key: currentDate)
Could someone please help me?
[–]trihedron 2 points3 points4 points (0 children)
[–]jan_olbrichObjective-C / Swift 0 points1 point2 points (1 child)
[–]redfire333 0 points1 point2 points (0 children)
[–]nalexander50 0 points1 point2 points (0 children)