I'm trying to figure out how to delete all saved User's data, and once that data is deleted, Signout the user and delete their account when deleteUserAccount() is called.
Right now, when the User presses the "Delete Account" button, their account gets deleted, but the data still remains on firebase because the completion handler gets called before the deleteAllUserTicketData() function has enough time to execute the query and delete the appropriate documents.
How can I wait for the queries to execute and all the documents to get deleted before executing the completion handler in order to sign the user out and delete their account?
func deleteAllUserTicketData(completion: @escaping () -> Void) {
let group = DispatchGroup()
group.enter()
self.rootWsrCollection?.whereField("uid", isEqualTo: userIdRef).getDocuments { (querySnapshot, err) in
guard let snapshot = querySnapshot else { return }
for wsr in snapshot.documents{
print("Deleting WSR: \(wsr)")
wsr.reference.delete()
}
group.leave()
}
group.enter()
self.rootExerciseCollection?.whereField("uid", isEqualTo: userIdRef).getDocuments { (querySnapshot, err) in
guard let snapshot = querySnapshot else { return }
for exercise in snapshot.documents {
print("Deleting Exercise: \(exercise)")
exercise.reference.delete()
}
group.leave()
}
group.enter()
self.rootWorkoutsCollection?.whereField("uid", isEqualTo: userIdRef).getDocuments { (querySnapshot, err) in
guard let snapshot = querySnapshot else { return }
for workout in snapshot.documents {
print("Deleting Workout: \(workout)")
workout.reference.delete()
}
group.leave()
}
group.notify(queue: DispatchQueue.global()) { [weak self] in
self?.workoutsCollection.daysCollection.removeAll()
print("Calling Notify Method")
completion()
}
}
//This method will only delete the user from the Firestore, but will not delete the User Auth credentials.
func deleteUserFromFirestore(completion: @escaping () -> Void) {
self.rootUserCollection?.whereField("uid", isEqualTo: userIdRef).getDocuments { (querySnapshot, err) in
guard let snapshot = querySnapshot else { return }
for user in snapshot.documents {
print("Deleting User: \(user)")
user.reference.delete()
}
completion()
}
}
func deleteUserAccount() {
deleteAllUserTicketData {
print("First Completion is called")
self.deleteUserFromFirestore {
print("Second Completion is called")
Auth.auth().currentUser?.delete()
}
}
}
}