'How can I fetch a list of data from firebase?
I am following a to-do list app tutorial from YouTube. I want to fetch a list of data from applications.
My code is like:
func fetchAllItems(completion: @escaping([TodoItem]) -> Void) {
guard let uid = Auth.auth().currentUser?.uid else { return }
var allItems = [TodoItem]()
ref.child("users").child(uid).child("applications").observe(.childAdded) { snapshot in
fetchSingleItem(id: snapshot.key) { item in
allItems.append(item)
print(allItems)
completion(allItems)
}
}
}
func fetchSingleItem(id: String, completion: @escaping(TodoItem) -> Void) {
guard let uid = Auth.auth().currentUser?.uid else { return }
ref.child("users").child(uid).child("applications").child(id).observeSingleEvent(of: .value) { snapshot in
guard let dictionary = snapshot.value as? [String: Any] else {
return
}
let todoItem = TodoItem(keyID: id, dictionary: dictionary)
print(todoItem)
completion(todoItem)
}
}
}
The struct of TodoItem is like:
struct TodoItem {
var title: String
var isComplete: Bool
init(keyID: String, dictionary: [String: Any]) {
self.title = dictionary["title"] as? String ?? ""
self.isComplete = dictionary["isComplete"] as? Bool ?? false
}
}
But when I print allItems, only the first one shows in console. Can anyone help me with this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|