Reputation: 948
When fetching firebase
data from a certain child
I write Database.database().reference().child["mychild1"]...
But what if I want to fetch data from all the available children at the same time? I tried Database.database().reference().child["mychild1"].["mychild2].["mychild3]...
but that didn't return anything? Is there a way to do this or do I need to fetch the data one child at a time?
EDIT
I omitted the .child
as suggested. And while this is likely the way to fetch all data, I suddenly didn't get anything at all from firebase
. Is there something additional from my firebase
logic that needs to be changed?
extension Reactive where Base: DatabaseReference {
func fetchFireBaseData() -> Observable<[Recipe]> {
return Observable.create { observer in
self.base.observeSingleEvent(of: .value, with: { snapshot in
guard let data = snapshot.children.allObjects as? [DataSnapshot] else { return }
let recipes = data.compactMap { dict -> Recipe? in
guard let value = dict.value as? NSDictionary else { return nil }
return Recipe(fbKey: dict.key,
recipeImageObject: value[FbKeyName.image.description] as? String ?? "",
recipeTextObject: value[FbKeyName.text.description] as? String ?? "",
recipeHeaderObject: value[FbKeyName.header.description] as? String ?? "",
isFavorite: UserDefaults.standard.favoriteRecipes.contains(dict.key))
}
observer.onNext(recipes)
observer.onCompleted()
})
return Disposables.create()
}
}
}
Upvotes: 0
Views: 57
Reputation: 317467
Database.database().reference()
returns a DatabaseReference object that represents the root of the entire database. You can fetch this reference, which will get all of its children, recursively, into a single snapshot. There is no need to use child() to get more specific references. Bear in mind this snapshot will occupy memory using all of the data in the database, so for a big database, this could cause you to run out of memory.
Upvotes: 1