首页 > 解决方案 > 更新文档 Firebase 时无限循环

问题描述

我尝试更新我的 Cloud Firestore 中的文档,该功能在应用程序生命周期的第一次点击时运行良好,但在第二次点击时,该函数启动并进入无限循环。

我试过了.update([Data]).set([Data])他们都在第一次点击时工作,第二次进入无限

func modifyInfoOwner(info: UserInfo){
    let fireStoreDB = Firestore.firestore()
    var documentID = ""
    fireStoreDB.collection("Users").whereField("email", isEqualTo: info.email).addSnapshotListener(includeMetadataChanges: false) { (snapshot, error) in
        if error != nil {
            print(error?.localizedDescription)
        } else {
            if snapshot?.isEmpty != true && snapshot != nil {
                for document in snapshot!.documents {
                    print("| saving info in DB")
                    print("v")
                    print(info)
                    documentID = document.documentID
                    //                        fireStoreDB.collection("Users").document(documentID)
                    fireStoreDB.collection("Users").document(documentID).setData(["adress" : info.adress, "name" : info.name, "phone" : info.phoneNumber, "seatQuantity" : info.seatQuantity, "email" : info.email, "token" : info.token]){ error in
                        if let error = error {
                            print("Data could not be saved: \(error).")
                        } else {
                            print("Data saved successfully!")
                        }
                    }
                }
            }
        }
    }
}

}

标签: swiftfirebasegoogle-cloud-firestore

解决方案


您正在更新您正在查询的同一个文档。并且由于您使用addSnapshotListener,侦听器在第一次获取数据后保持活动状态。因此,当您调用setData文档时,您的侦听器会再次被触发,这会导致它setData再次触发,这就是您的无限循环。

这里的解决方案是使用getDocuments而不是addSnapshotListener. 使用getDocuments,您只读取一次数据,因此更新不会再次触发它。

fireStoreDB.collection("Users")
  .whereField("email", isEqualTo: info.email)
  .getDocuments(includeMetadataChanges: false) { (snapshot, error) in
      ...

您的其余代码不必更改。


推荐阅读