Search code examples
swiftfirebase-authenticationfirebaseui

How to Sign out and Delete Users Register By FirebaseUI Swift 5


I want to give my app the ability to Log out/delete the user and when I type this code

    @IBAction func deleteTheAccountButtonHasBeenTapped(_ sender: Any) {
    
    let user = Auth.auth().currentUser
    var credential: AuthCredential
    
    user?.reauthenticateAndRetrieveData(with: credential, completion: {(authResult, error) in
        if let error = error {
            // An error happened.
            print(error)
        }else{
            //user re-authenticated
            user?.delete { error in
              if let error = error {
                // An error happened.
                print(error)
              } else {
                // Account deleted.
                let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
                self.present(vc, animated:true, completion:nil)
              }
            }
            
        }
    })
}

I got this error:

Variable 'credential' used before being initialized

any one can help me?


Solution

  • The error message is pretty explicit: you're using credential before you initialized it.

    In order to delete the user, you need to first reauthenticate them, as shown in the documentation on reauthenticating the user. Your version doesn't implement this comment from that code:

    // Prompt the user to re-provide their sign-in credentials
    

    How to reauthenticate the user depends on the provider. For example for email/password, you'd get them with:

    credential = EmailAuthProvider.credential(withEmail: email, password: password)
    

    A handy place to find similar snippets for other providers is in the documentation on linking accounts.