ios - 我应该如何使用 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
}
}
}
解决方案
该类根本没有init()
- 所以该fetchData()
函数实际上并没有被调用。
尝试添加
init() {
self.fetchData()
}
推荐阅读
- python - python中对象调用函数的开关实现
- python-3.x - Python如何将n个元素的组从列表转换为它们的平均值
- c++ - 引用禁用复制构造函数/赋值的对象
- typescript - 在 TypeScript 中使用 proxyquire 和 sinon 存根 adm-zip
- python - python - 如何通过odeint在python中返回所有内部定义的时间步的值
- javascript - 水平菜单悬停延迟 CSS/JS
- excel - 如果条件在另一列中的每个值至少存在一次,则对一列中的值求和
- excel - 将工作簿范围分配给变量 - 类型不匹配
- mongodb - Spring中@Aggregation注解的聚合查询
- database - 是否可以使用无状态逻辑(无数据库)使令牌无效?