更新文档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
...

代码的其余部分不必更改。

最新更新