swift - 更新文档 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!")
}
}
}
}
}
}
}
}
解决方案
您正在更新您正在查询的同一个文档。并且由于您使用addSnapshotListener
,侦听器在第一次获取数据后保持活动状态。因此,当您调用setData
文档时,您的侦听器会再次被触发,这会导致它setData
再次触发,这就是您的无限循环。
这里的解决方案是使用getDocuments
而不是addSnapshotListener
. 使用getDocuments
,您只读取一次数据,因此更新不会再次触发它。
fireStoreDB.collection("Users")
.whereField("email", isEqualTo: info.email)
.getDocuments(includeMetadataChanges: false) { (snapshot, error) in
...
您的其余代码不必更改。
推荐阅读
- c - 如何从 .txt 文件中读取已知数量的未知大小的字符串并将每一行存储在矩阵的一行中(在 C 中)?
- c# - 旋转时控制混乱
- python - Pandas Dataframe 用 stack 和 unstack 重塑
- php - laravel 部分破坏了 flowe 的其余部分
- javascript - AngularJS:ng-repeat 检测组更改
- java - 从 Vert.x 调用多个呼出电话
- java - 用于测试 RabbitMQ 消费者和生产者的 JUnit 测试
- html - 边距正在移动父容器和子 div 而不仅仅是子 div
- reactjs - react native redux dispatch outside component is not trigger componentWillReceiveProps
- python - 如何连接到在 docker 实例中运行的 spark