I have three nodes in firebase that I would like to loop through using the same loop. I\'m successfully able to loop through a single node (cookies) using this code:
<
You can convert snapshot to dict and loop through the dict:
databaseRef.child("cookies").observeSingleEvent(of: .value, with: { snapshot in
if let dict = snapshot.value as? Dictionary<String, Dictionary<String, Any>> {
for (key, value) in dict {
if let recipeHeader = value["recipeHeaderFirebase"] as? String, favoriteArray.contains(key) {
self.numberOfRecipes.append(recipeHeader)
...
}
}
}
}
or you can use the enumerator:
databaseRef.child("cookies").observeSingleEvent(of: .value, with: { snapshot in
let enumerator = snapshot.children
while let (key, value) = enumerator.nextObject() as? FIRDataSnapshot {
if let recipeHeader = value["recipeHeaderFirebase"] as? String, favoriteArray.contains(key) {
self.numberOfRecipes.append(recipeHeader)
...
}
}
}
The following code prints all three levels of snapshots. I hope this will help:
self.databaseRef.child("cookies").observeSingleEvent(of: .value, with: { (cookiesSnapshot) in
print("cookies snapshot: \(cookiesSnapshot)")
self.databaseRef.child("dessert").observeSingleEvent(of: .value, with: { (dessertSnapshot) in
print("dessert snapshot: \(dessertSnapshot)")
self.databaseRef.child("breakfast").observeSingleEvent(of: .value, with: { (breakfastSnapshot) in
print("breakfast snapshot: \(breakfastSnapshot)")
})
})
})
I can't check this, so I hope all the } and ) are at the right place. :)