I am working on a Swift/SwiftUI application and using Firebase's real-time database for data storage.
Currently, I am stuck trying to get data for a specific child in the database. I have tried multiple solutions I found on StackOverflow but for me, it just keeps coming back empty.
This is the current structure I have for the database:
What I am trying to do with the code is once I enter a list, I want to use the listID (which is the same as the key) to extract all the items that belong to this list.
My most recent approach was the following:
var listItems: [String] = []
class FirebaseSession: ObservableObject {
@Published var listItems: [String] = []
var ref: DatabaseReference = Database.database().reference()
func getSingleList(id: String) {
ref.child("Lists").child("\(id)".child("listItems").observe(DataEventType.value) { (snapshot) in
self.listItems = []
for child in snapshot.children {
if let snapshot = child as? DataSnapshot
{
self.listItems.append(snapshot.key)
}
}
}
}
}
struct ListView: View {
@ObservedObject var session = FirebaseSession()
var body: some View {
VStack {
...
}
.onAppear() {
session.getSingleList(id: self.listId)
}
}
But whenever I run this code my listItems variable is always empty.
Any help is greatly appreciated!
