繁体   English   中英

我应该如何使用 Firestore 使用 SwiftUI 制作动态视图

[英]How should I use Firestore to make a dynamic view with 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
    }
}
}

class 根本没有init() - 所以fetchData() function 实际上并没有被调用。

尝试添加

init() {
    self.fetchData()
}

init() 或线程没有问题。 我现在不需要将此 object 添加到 SceneDelegate。 所以,我只需要将.environmentObject(ExViewModel()) 添加到我的主视图中

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: MotherView().environmentObject(ExViewModel()))
        self.window = window
        window.makeKeyAndVisible()
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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