In my SettingsViewModel I have the following:
class SettingsViewModel: ObservableObject {
func deleteUser(){
let userId = Auth.auth().currentUser!.uid
Firestore.firestore().collection("users").document(userId).delete() { err in
if let err = err {
print("error: \(err)")
} else {
print("Deleted user in db users")
Storage.storage().reference(forURL: "gs://myapp.appspot.com").child("avatar").child(userId).delete() { err in
if let err = err {
print("error: \(err)")
} else {
print("Deleted User image")
Auth.auth().currentUser!.delete { error in
if let error = error {
print("error deleting user - \(error)")
} else {
print("Account deleted")
}
}
}
}
}
}
}
}
In my setting view im calling the function in a button like so:
#ObservedObject var settingsViewModel = SettingsViewModel()
func logout() {
session.logout()
}
Button(action: {
self.showActionSheet = true
}) {
Text("Delete Account").foregroundColor(.white).padding()
}.background(Color.red)
.cornerRadius(10)
.padding(.top, 35)
.actionSheet(isPresented: self.$showActionSheet) {
ActionSheet(title: Text("Delete"), message: Text("Are you sure you want to delete your account?"),
buttons: [
.default(Text("Yes, delete my account."), action: {
self.deleteUser()
self.session.logout()
self.showActionSheet.toggle()
}),.cancel()
])
}
This doesn't work correctly as it deletes the account:
Auth.auth().currentUser!.delete { error in
if let error = error {
print("error deleting user - \(error)")
} else {
print("Account deleted")
}
}
And then signs out, leaving the other data, but if i remove:
Auth.auth().currentUser!.delete { error in
if let error = error {
print("error deleting user - \(error)")
} else {
print("Account deleted")
}
}
then it deletes the user data, but then doesn't delete the storage:
Storage.storage().reference(forURL: "gs://myapp.appspot.com").child("avatar").child(userId).delete()
Im trying to get it to flow so it deletes the user data, then the image, then the auth data and then logout out the app. all the functions work, but putting them together is causing an issue.
The recommended way for doing this is:
Write a Cloud Function that triggers when the user account is deleted in Firebase Auth (see user.onDelete())
In this function, delete all the user's data in Cloud Firestore, Cloud Storage
Trigger the function by deleting the user by calling user.delete()
You might want to check out the Delete User Data Extension, which covers step 1 and 2 for you.
Related
I have an app that allows a user to sign in and sign out. As per App Store rules, I have to allow a user to be able to delete their account. I am using the default function from Firebase to delete account:
func deleteUser() {
let user = Auth.auth().currentUser
user?.delete { error in
if let error = error {
print("Error with deleting user")
} else {
print("User Deleted")
try? Auth.auth().signOut()
self.userisLoggedIn = false
}
}
}
But when I check my firebase auth, the user is still there. I still get the User Deleted print dialouge.
Button to fix the view:
Button {
do {
try deleteUser()
} catch {
print("error with deleting user")
}
} label: {
Text("Delete My Account")
}.buttonStyle(.bordered)
let washingEvent = HKCategoryType.categoryType(forIdentifier: .handwashingEvent)!
healthStore.execute(query)
healthStore.enableBackgroundDelivery(
for: washingEvent,
frequency: .immediate,
withCompletion: { succeeded, error in
print("enableBackgroundDelivery")
if let unwrappedError = error {
print("could not enable background delivery: \(unwrappedError)")
}
if succeeded {
print("background delivery enabled")
}
print(error)
//here I send data to my server .
return
}
// Background delivery is enabled
}
)
let query2 = HKObserverQuery(
sampleType: washingEvent,
predicate: nil,
updateHandler: { query, completionHandler, error in
print("error in \(error)")
defer {
completionHandler()
}
guard error != nil else {
return
}
// TODO
})
healthStore.execute(query2)
I added washingEvent but after app is gone background and I washed with Apple Watch well, but not receiving any from my server. it seems it didn't come to call back of enableBackgroundDelivery or erverQueHKry ...
how can I get Information when background ?
This question already has an answer here:
Move path from Storage to Realtime Database in Firebase
(1 answer)
Closed 1 year ago.
I have successfully added imgae file to Storage, but I don't know how can I move the path file image in Storage to Realtime Database so it can be displayed on UI.
In my Realtime database there is a field to contain the path of the image
I want to move path p4.jpg in Storage to image field in Realtime Database
func Update image to storage
func uploadImageToStorage(image: UIImage) {
if let imageData = image.jpegData(compressionQuality: 1) {
let storage = Storage.storage()
storage.reference().child("").putData(imageData, metadata: nil) {( _, error) in
if let error = error {
print("an error has occured - \(error.localizedDescription)")
} else {
print("image uploaded successfully")
}
}
} else {
print("Coldn't unwrap/case imgae to data")
}
}
let imageURL = UIImage(named:"")
Button(action: {
profileViewModel.uploadImageToFirebse(image: imgaeURL )
}) {
Text("Upload Image")
}
In your case, you need two functions: upload the image to storage, then upload the url to database.
func uploadImageToStorage(image: UIImage) {
if let imageData = image.jpegData(compressionQuality: 1) {
let storage = Storage.storage()
let photoRef = storage.reference().child("avatar/filename.jpg")
photoRef.putData(imageData, metadata: nil) {( _, error) in
if let error = error {
print("an error has occured - \(error.localizedDescription)")
} else {
photoRef.downloadURL { url, err in
if let url = url {
// call function to add this url to database
} else {
// you might want to delete the image from storage
print("could not get download url")
}
}
print("image uploaded successfully")
}
}
} else {
print("Coldn't unwrap/case imgae to data")
}
}
I was reading up on this question about app freezes and semaphores and I tried to implement the answer into my code, but it still freezes my app despite calling the UI work on the main thread. My goal is to stop the app from freezing once all the entries are called and have the UI work continue like normal.
This is the alert action I have in the deletion method so far:
let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { (deletion) in
let semaphore = DispatchSemaphore(value: 0)
self.deleteButton.isHidden = true
self.loadingToDelete.alpha = 1
self.loadingToDelete.startAnimating()
DispatchQueue.global(qos: .userInitiated).async {
self.db.collection("student_users/\(user.uid)/events_bought").getDocuments { (querySnapshot, error) in
guard error == nil else {
print("The docs couldn't be retrieved for deletion.")
return
}
guard querySnapshot?.isEmpty == false else {
print("The user being deleted has no events purchased.")
return
}
for document in querySnapshot!.documents {
let docID = document.documentID
self.db.collection("student_users/\(user.uid)/events_bought/\(docID)/guests").getDocuments { (querySnap, error) in
guard querySnap?.isEmpty == false else {
print("The user being deleted has no guests with his purchases.")
return
}
for doc in querySnap!.documents {
let guest = doc.documentID
self.db.document("student_users/\(user.uid)/events_bought/\(docID)/guests/\(guest)").delete { (error) in
guard error == nil else {
print("Error deleting guests while deleting user.")
return
}
print("Guests deleted while deleting user!")
semaphore.signal()
}
semaphore.wait()
}
}
}
}
self.db.collection("student_users/\(user.uid)/events_bought").getDocuments { (querySnapshot, error) in
guard error == nil else {
print("There was an error retrieving docs for user deletion.")
return
}
guard querySnapshot?.isEmpty == false else {
return
}
for document in querySnapshot!.documents {
let docID = document.documentID
self.db.document("student_users/\(user.uid)/events_bought/\(docID)").delete { (err) in
guard err == nil else {
print("There was an error deleting the the purchased events for the user being deleted.")
return
}
print("Purchases have been deleted for deleted user!")
semaphore.signal()
}
semaphore.wait()
}
}
self.db.document("student_users/\(user.uid)").delete(completion: { (error) in
guard error == nil else {
print("There was an error deleting the user document.")
return
}
print("User doc deleted!")
semaphore.signal()
})
semaphore.wait()
user.delete(completion: { (error) in
guard error == nil else {
print("There was an error deleting user from the system.")
return
}
print("User Deleted.")
semaphore.signal()
})
semaphore.wait()
DispatchQueue.main.async {
self.loadingToDelete.stopAnimating()
self.performSegue(withIdentifier: Constants.Segues.studentUserDeletedAccount, sender: self)
}
}
}
So this actually deletes everything cleanly with no residual data in the Firestore database, which is what I wanted to happen all along, the only issue is that the app freezes. I thought that the answer in the question I linked above would work in my case, but it didn't.
Also to mention, I've had suggestions of using Cloud Functions for this issue but my app has two types of users with different logic and syntax in the deletion process so I couldn't just use a simple auth().onDelete() in Cloud Functions and clean up residue. Even if I could, it would be the same issue I'm facing here but just on the server side, trying to order the tasks correctly, which in my opinion is repetitive and not the most sensible thing to do at this point.
Any other suggestions to overcome this issue? Thanks in advance.
EDIT Since semaphores are not the way to go, I resorted to this :
let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { (deletion) in
self.deleteButton.isHidden = true
self.loadingToDelete.alpha = 1
self.loadingToDelete.startAnimating()
self.db.collection("student_users/\(user.uid)/events_bought").getDocuments { (querySnapshot, error) in
guard error == nil else {
print("The docs couldn't be retrieved for deletion.")
return
}
guard querySnapshot?.isEmpty == false else {
print("The user being deleted has no events purchased.")
return
}
for document in querySnapshot!.documents {
let docID = document.documentID
self.db.collection("student_users/\(user.uid)/events_bought/\(docID)/guests").getDocuments { (querySnap, error) in
guard querySnap?.isEmpty == false else {
print("The user being deleted has no guests with his purchases.")
return
}
let group = DispatchGroup()
for doc in querySnap!.documents {
let guest = doc.documentID
group.enter()
self.db.document("student_users/\(user.uid)/events_bought/\(docID)/guests/\(guest)").delete { (error) in
guard error == nil else {
print("Error deleting guests while deleting user.")
return
}
print("Guests deleted while deleting user!")
group.leave()
}
}
}
}
}
self.db.collection("student_users/\(user.uid)/events_bought").getDocuments { (querySnapshot, error) in
guard error == nil else {
print("There was an error retrieving docs for user deletion.")
return
}
guard querySnapshot?.isEmpty == false else {
return
}
let group = DispatchGroup()
for document in querySnapshot!.documents {
let docID = document.documentID
group.enter()
self.db.document("student_users/\(user.uid)/events_bought/\(docID)").delete { (err) in
guard err == nil else {
print("There was an error deleting the the purchased events for the user being deleted.")
return
}
print("Purchases have been deleted for deleted user!")
group.leave()
}
}
}
self.db.collection("student_users").whereField("userID", isEqualTo: user.uid).getDocuments { (querySnapshot, error) in
guard error == nil else {
print("There was an error deleting the user document.")
return
}
guard querySnapshot?.isEmpty == false else {
return
}
let group = DispatchGroup()
for document in querySnapshot!.documents {
let docID = document.documentID
group.enter()
self.db.document("student_users/\(docID)").delete { (err) in
guard err == nil else {
return
}
print("User doc deleted!")
group.leave()
}
}
}
let group = DispatchGroup()
group.enter()
user.delete(completion: { (error) in
guard error == nil else {
print("There was an error deleting user from the system.")
return
}
print("User Deleted.")
group.leave()
})
group.notify(queue: .main) {
self.loadingToDelete.stopAnimating()
self.performSegue(withIdentifier: Constants.Segues.studentUserDeletedAccount, sender: self)
}
}
This still leaves residual data and does not execute the tasks in order. Any other suggestions?
Let me give you some ideas because I think your solution should incorporate some or all of these. First is how dispatch groups work and how you can nest them to execute blocks of async tasks in order:
func deleteUser(completion: #escaping (_ done: Bool) -> Void) {
// put UI into loading state
db.collection("someCollection").getDocuments { (snapshot, error) in
if let snapshot = snapshot {
if snapshot.isEmpty {
completion(true) // no errors, nothing to delete
} else {
let dispatchGroup = DispatchGroup() // instantiate the group outside the loop
var hasErrors = false
for doc in snapshot.documents {
dispatchGroup.enter() // enter on every iteration
db.document("someDocument").delete { (error) in
if let error = error {
print(error)
hasErrors = true
}
dispatchGroup.leave() // leave on every iteration regardless of outcome
}
}
dispatchGroup.notify(queue: .main) {
if hasErrors {
completion(false) // failed to delete
} else {
// execute next task and repeat
}
}
}
} else {
if let error = error {
print(error)
completion(false) // failed to delete
}
}
}
}
deleteUser { (done) in
if done {
// segue to next view controller
} else {
// retry or alert user
}
}
The example above is the basics of how dispatch group can work for you. When you leave the group the same number of times you've entered it, the completion handler is called. This example does not have any recursion and doesn't check if everything was actually deleted. Here is an example of how you could add some of that:
func deleteUser(completion: #escaping (_ done: Bool) -> Void) {
var retries = 0
func task() {
db.collection("someCollection").getDocuments { (snapshot, error) in
if let snapshot = snapshot {
if snapshot.isEmpty {
completion(true) // done, nothing left to delete
} else {
// delete the documents using a dispatch group or a Firestore batch delete
task() // call task again when this finishes
// because this function only exits when there is nothing left to delete
// or there have been too many failed attempts
}
} else {
if let error = error {
print(error)
}
retries += 1 // increment retries
run() // retry
}
}
}
func run() {
guard retries < 5 else {
completion(false) // 5 failed attempts, exit function
return
}
if retries == 0 {
task()
} else { // the more failures, the longer we wait until retrying
DispatchQueue.main.asyncAfter(deadline: .now() + Double(retries)) {
task()
}
}
}
run()
}
This doesn't answer your question directly but it should help you with the task overall. You can also forego some of the looping and deleting and do it all inside a Firestore batch operation, which comes with its own completion handler. There are lots of ways to tackle this but these are some things I'd consider.
I'm setting up a shareExtension in iOS and want to use the FirebaseSDK to upload data direct instead of using AppGroups. This works as expected, but after 1 hour the UserToken get's invalidated and i can't reach the Firestore Backend anymore.
I'm using the FirebaseSDK (6.2.0) and enabled Keychain sharing to access the current signedIn User. I have the same Google-Plist in the MainApp and the shareExtension. The data gets also uploaded correctly from the shareExtension and was also updated via the snapshotListener in the MainApp.
Relevant code in the MainApp
lazy var db = Firestore.firestore()
//TEAMID form the Apple Developer Portal
let accessGroup = "TEAMID.de.debug.fireAuthExample"
override func viewDidLoad() {
super.viewDidLoad()
do {
try Auth.auth().useUserAccessGroup("\(accessGroup)")
} catch let error as NSError {
print("Error changing user access group: %#", error)
}
guard let user = Auth.auth().currentUser else {
self.statusLabel.text = "user get's lost"
return
}
statusLabel.text = "UserID: \(user.uid)"
// Do any additional setup after loading the view.
db.collection("DummyCollection").addSnapshotListener { (querySnapshot, error) in
if let err = error {
print(err.localizedDescription)
}
guard let snapshot = querySnapshot else {
return
}
DispatchQueue.main.async {
self.dbCountLabel.text = "\(snapshot.count)"
}
}
}
func signIN(){
// https://firebase.google.com/docs/auth/ios/single-sign-on
do {
try Auth.auth().useUserAccessGroup("\(accessGroup)")
} catch let error as NSError {
print("Error changing user access group: %#", error)
}
Auth.auth().signInAnonymously { (result, error) in
if let err = error{
print(err.localizedDescription)
return
}
print("UserID: \(Auth.auth().currentUser!.uid)")
}
}
}
}
Code in the shareExtension:
override func viewDidLoad() {
super.viewDidLoad()
if FirebaseApp.app() == nil {
FirebaseApp.configure()
}
do {
try Auth.auth().useUserAccessGroup(accessGroup)
} catch let error as NSError {
print("Error changing user access group: %#", error)
}
tempUser = Auth.auth().currentUser
if tempUser != nil {
userIDLabel.text = "UserID: \(tempUser!.uid)"
doneButton.isEnabled = true
db.collection("DummyCollection").addSnapshotListener { (querySnapshot, error) in
if let err = error {
print(err.localizedDescription)
}
guard let snapshot = querySnapshot else {
return
}
DispatchQueue.main.async {
self.dataCountLabel.text = "\(snapshot.count)"
}
}
} else {
// No user exists in the access group
self.navigationItem.title = "No User"
}
}
I expect that this should be possible, but the Token gets somehow invalid in the MainApp and i could not reach the Firestore backend.
6.2.0 - [Firebase/Auth][I-AUT000003] Token auto-refresh re-scheduled in 01:00 because of error on previous refresh attempt.
6.2.0 - [Firebase/Firestore][I-FST000001] Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: An internal error has occurred, print and inspect the error details for more information.
Answering my own question: This should be fixed in the next release (Firebase 6.4.0) Details can be found in this PR 3239.