我将我的应用程序连接到 Firestore。一切正常,除了我的数据在我启动应用程序时第一次没有显示。当我在选项卡之间切换时,数据会显示。它的作用就像 [Place] 数组在我的应用程序显示后缓慢附加。如何强制在第一次加载时显示数据?这是代码:
class FirebaseManager: ObservableObject {
@Published var places = [Place]()
init() {
fetchData()
}
func fetchData(){
Firestore.firestore().clearPersistence()
let db = Firestore.firestore()
db.collection("places").addSnapshotListener { (snap, err) in
if err != nil{
print((err?.localizedDescription)!)
return
}
self.places.removeAll()
for i in (snap?.documentChanges)!{
let name = i.document.data()["name"] as! String
let type = i.document.data()["type"] as! String
let desc = i.document.data()["desc"] as! String
let image = i.document.data()["image"] as! String
let loc = i.document.data()["loc"] as! String
let contact = i.document.data()["contact"] as! String
let fol = i.document.data()["followers"] as! String
DispatchQueue.main.async {
self.places.append(Place(id: fol, name: name, type: type, description: desc, image: image, location: loc, contact: contact))
print(name)
}
}
}
}
}
struct topView : View {
@ObservedObject var firebaseMan = FirebaseManager()
var body : some View{
VStack(alignment: .leading, spacing: 15){
Text("Clubs & Places")
.font(.system(size: 25, weight: .regular))
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 15){
ForEach(0 ..< firebaseMan.places.count) {i in
Image(self.firebaseMan.places[i].image)
我尝试使用 .onAppear{... 查看,但这也没有帮助。 谢谢。
最佳答案
解决了!这段代码没问题,但是在 SwiftUI ScrollView 中存在一个问题,它没有刷新 observasble 对象! ScrollView 之后总是检查 (your @Published var) =!零!我希望苹果能尽快在下一次更新中解决这个问题。
关于ios - SwiftUI Firestore 数据在第一次加载时不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59582759/