简体   繁体   中英

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

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!

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)
                        }
                    }
                }
            }
        }
    }


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM