ios - SwiftUI Firestore 数据在第一次加载时不显示

标签 ios swift google-cloud-firestore

我将我的应用程序连接到 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/

相关文章:

iphone - 究竟什么时候*必须*应用程序包含 Reachability 类来测试网络可达性?

ios - 强制用户在 iOS 中以编程方式更新应用程序

swift - Swift 中的 TableView 高度

ios - 如何计算得分速度?

firebase - Flutter - 从 firestore 循环获取数据

ios - swift : UIPercentDrivenInteractiveTransition on cancel?

ios - 无法将需要作为 UICollectionView 单元格的 View 出队

swift - 如果至少有一个案例具有关联值,则无法比较两个枚举

java - 无法在片段(发布版本)中启动 RecyclerView,但在(调试版本)中工作完美

firebase - Firestore 身份验证用户