[英]How should I use Firestore to make a dynamic view with SwiftUI
I have no goal of dynamically updating the screen without restarting the application.我没有在不重新启动应用程序的情况下动态更新屏幕的目标。 But even so, I cannot do it.
但即便如此,我也做不到。 First, the screen is shown, and then the data is requested from the database So, i see the empty view.
首先,显示屏幕,然后从数据库请求数据所以,我看到了空视图。 Maybe i can't fully understand how the threads are working and problem is here
也许我无法完全理解线程是如何工作的,问题就在这里
I wanna use info from the Firestore in my view我想在我的视图中使用来自 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()
}
}
}
And here how i get my data在这里我如何获取我的数据
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
}
}
}
That class doesn't have an init()
at all - so the fetchData()
function isn't actually getting called. class 根本没有
init()
- 所以fetchData()
function 实际上并没有被调用。
Try adding尝试添加
init() {
self.fetchData()
}
There's no problem with init() or threads. init() 或线程没有问题。 I don't now that I need to add this object to SceneDelegate.
我现在不需要将此 object 添加到 SceneDelegate。 So, i just need to add.environmentObject(ExViewModel()) to my main view
所以,我只需要将.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.