Search code examples
google-cloud-firestoreswiftuiswiftui-foreach

I cant present my view with foreach in SwiftUI


I try to present a View-struct as often as there are items in an array. I want to use for-each, because I don't like the UIList view. Btw I'm using SwiftUI. I generate the array which I want to use from firebase-firestore.

Here is how I generate my array:

class ViewModellForItems: ObservableObject{
    @Published var listItemsEnglisch = [MaterialItemClass]()
    
    let myDataBase = Firestore.firestore()

    let Ordner = Firestore.firestore().collection("Censored")
    
    func updateData(){
        Ordner.addSnapshotListener { (querySnapshot, error) in
            guard let documents = querySnapshot?.documents else {
                print("Ordner wurde nicht gefunden")
                return
            }
            self.listItemsMathe = documents.map { (queryDocumentSnapshot) -> MaterialItemClass in
                
                let data = queryDocumentSnapshot.data()
                
                let Name = data["Name"] as? String ?? ""
                let beschreibung = data["beschreibung"] as? String ?? ""
                let anzahlDesProduktes = data["anzahlDesProduktes"] as? Int ?? 0
                let bildName = data["bildName"] as? String ?? ""
                let hintergrundFarbe = data["hintergrundFarbe"] as? String ?? ""
                
                let item = MaterialItemClass(Name: Name, beschreibung: beschreibung, anzahlDesProduktes: anzahlDesProduktes, bildName: bildName, hintergrundFarbe: hintergrundFarbe)
                return item
                
            }
            
        }
    }
}

Here is the Struct that I use in the ViewModellForItems Class:

   struct MaterialItemClass {
        var Name: String
        var beschreibung: String
        var anzahlDesProduktes: Int
        var bildName: String
        var hintergrundFarbe: String
    }

And here is my ContendView.swift File:

struct ContendView: View {
    
    
    @ObservedObject private var viewModel = ViewModellForItems()
    
    var body: some View {
        
        ForEach(0 ..< viewModel.listItemsEnglisch.count, id: \.self) {
            
            Text(viewModel.listItemsEnglisch[$0].Name)
          
                }.onAppear(){
                    self.viewModel.updateData()
                }        
                Text("Debug")
                
    }
}

I only get presented the Debug-Text... what am I doing wrong? And further; how can I present a whole View-Struct for each element I this array?

Just want to say, there's no fail of the firebase, because if I run almost the same code in a list view, everything is working fine...


Solution

  • Ok boys I got my mistake, if I update my Array only in the .onAppear Methode of my for each block, it won't update, because the for-each block will never appear. Thanks for your time Boothosh