How to get array of data from a child node in Swift and Firebase?

Viewed 21

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:

enter image description here

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!

1 Answers

So far I have been able to find a workaround.

Instead of making the request with the listID, I am loading all the records on init() and then using that stored variable to filter the relevant records.

    func getLists() {
        ref.child("Lists").observe(DataEventType.value) { (snapshot) in
            self.listItems = []
            for child in snapshot.children {
                if let snapshot2 = child as? DataSnapshot
                {
                    let listId = snapshot2.key
                    let childSnapshot = snapshot2.childSnapshot(forPath: "listItems")
                    for child2 in childSnapshot.children {
                        if let snapshot3 = child2 as? DataSnapshot {
                            let itemId = snapshot3.key
                            let newRow = leagueSearch(listId: listId,
                                                      itemId: itemId)
                            self.listItems.append(newRow)
                        }
                    }
                }
            }
        }
    }


Related