首页 > 解决方案 > 我应该如何使用 Firestore 通过 SwiftUI 制作动态视图

问题描述

我没有在不重新启动应用程序的情况下动态更新屏幕的目标。但即便如此,我也做不到。首先,显示屏幕,然后从数据库请求数据所以,我看到了空视图。也许我无法完全理解线程是如何工作的,问题就在这里

我想在我的视图中使用来自 Firestore 的信息

struct Exercises: View {

@ObservedObject private var viewModel = ExViewModel()

var body: some View {
    VStack {
        ScrollView{
            ForEach(viewModel.exData) { exData in
                if exData.isShow {
                    NavigationLink(destination: CarouselView(navBarTitle: exData.name, data: exData.cards, dataIds: exData.cardsId)) {
                        ButtonView(title: exData.name)
                    }
                }
            }
        }
        AdBannerView()
    }
    .navigationBarTitle("Упражнения")
    .onAppear(){
        self.viewModel.fetchData()
        
    }
}
}

在这里我如何获取我的数据

class ExViewModel: ObservableObject{
@Published var exData = [ExercisesData]()

private var db = Firestore.firestore()

func fetchData() {
    let rootCollection = db.collection("exercises")

    var ex : [ExercisesData] = []
    
    
    rootCollection.getDocuments() { (querySnapshot, err) in
        
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
            
                let name = document.data()["name"] as? String ?? ""
                let isShow = document.data()["isShow"] as? Bool ?? false
                let cardsId = document.data()["cardsId"] as? [String] ?? []
                                    
                ex.append(ExercisesData(id: document.documentID, name: name, isShow: isShow, cardsId: cardsId))
                
            }  
        }
        self.exData = ex
    }
}
}

标签: iosgoogle-cloud-firestoreswiftui

解决方案


该类根本没有init()- 所以该fetchData()函数实际上并没有被调用。

尝试添加

init() {
    self.fetchData()
}

推荐阅读