我想删除 Firestore 中的用户帐户及其所有文档,但通过异步查询,Firebase 会先删除该帐户,然后再删除所有文档。
因此,我收到身份验证错误,因为当 firestorm 删除最后的文档时,用户不再存在。
db.collection("users").document(self.user.uid).collection("sachets").getDocuments() { (QuerySnapshot, err) in
if let err = err{
print("Erreur de lecture : \(err)")
} else {
for document in QuerySnapshot!.documents {
db.collection("users").document(self.user.uid).collection("sachets").document(document.documentID).delete(){ err in
if let err = err {
print(" 🔴 Probleme de suppression des docuemnts \(err)")
} else {
print(" 🔵 Documents supprimés")
}
}
}
}
}
self.user?.delete { error in
if let error = error {
print(" 🔴 Probleme de suppression du compte Utilisateur \(error)")
} else {
print(" 🔵 Utilisateur supprimé")
}
}
谁能告诉我怎么办? 谢谢
最佳答案
好吧,我建立了一个测试项目并解决了这个问题。您还需要确保删除用户字段中的所有数据。例如,如果您在 user
节点上有 name
、age
等。
首先我创建了一个函数来获取当前用户uid
:
func currentUser() -> String {
return Auth.auth().currentUser!.uid
}
然后我创建了一个函数来删除登录用户的所有数据。这将首先删除所有子集合数据,然后删除 userID
的文档。
要处理异步方法,您可以使用 DispatchGroup
来通知所有异步调用何时完成。
附注:如果无法 100% 保证存在文档,请确保决不强制解包值。否则,您的应用程序可能会崩溃。要解决此问题,请使用 guard
或 if let
来解决此问题。
// Where "user" is the result from currentUser()
func removeData(from user: String) {
db.collection("users").document(user).collection("sachets").getDocuments { (snapshot, error) in
if let error = error {
// Handle error
} else if let documents = snapshot?.documents {
// Using if let to see if there are documents
// Time to delete all the subCollection for the user
self.deleteSubCollectionData(for: user, documents, completion: {
// Once that done, make sure to delete all the fields on the highest level.
self.db.collection("users").document(user).delete(completion: { (error) in
if let error = error {
// Handle error
} else {
// Delete the account
self.deleteAccount()
}
})
})
}
}
}
// This function will remove the subCollectionData
fileprivate func deleteSubCollectionData(for user: String, _ documents: [QueryDocumentSnapshot], completion: @escaping () -> ()) {
let group = DispatchGroup()
documents.forEach({
group.enter()
self.db.collection("users").document(user).collection("sachets").document($0.documentID).delete(completion: { (error) in
if let error = error {
// Handle error
}
group.leave()
})
})
// Once the dispatchGroup is done...
group.notify(queue: .main) {
completion()
}
}
最后...
func deleteAccount() {
Auth.auth().currentUser?.delete { (error) in
if let error = error {
print(error)
} else {
print("Deleted account")
}
}
}
如果您不删除所有级别的数据,那么 Firestore 中仍然会有数据。
关于swift - 使用 Firestore 删除帐户和文档时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53083511/