1
votes

I am creating an application which authenticate user using PhoneAuth. In my application I have a function which let user add Email to his account But not meant that I authenticate user using Email and Password, I just want to add email to his/her account (auth.auth().currentUser).

Initially, I let user to add his/her email in textfield and then I start to logout user from his/her device in order to reauthentication otherwise, I cannot update user's email using auth.updateEmail(). But sadly, the credential always expired after I called func updateEmail().

This is how I signIn user and update Email

let credential = PhoneAuthProvider.provider().credential(withVerificationID: verficationID, verificationCode: code)
    Auth.auth().signInAndRetrieveData(with: credential) { (result, error) in

        guard let result = result else {
            completion(false)
            return
        }
        if error == nil {

            guard let user = Auth.auth().currentUser else {
                return
            }

            if UserDefaults.standard.getUserUpdatedEmail() {

                user.reauthenticate(with: credential, completion: { (error) in

                if error == nil {

                    user.updateEmail(to: newEmail, completion: { (error) in

                    if error == nil {
                      UserDefaults.standard.setUserUpdatedEmail(value: false)
                       completion(true)
                    //return true
                    } else {
                       completion(false)
                    //return false
                      print("Error validate email ",error?.localizedDescription ?? "")
                    }

                })
           } else {

            completion(false)
           // return false
                print("Error reauthntication email ",error?.localizedDescription ?? "")
        }
    })

            } else {

                print("User is signed in \(result.user)")

                print("This is userID \(result.user.uid)")

                completion(true)

            }

        } else {

            if let error = error {
                print("Error during verification \(error.localizedDescription)")
            }
            completion(false)

        }

    }

I don't why the credential is expired too fast? I cannot figure it out how to update user email using PhoneAuthCredential. Is there any other techniques to do it?

1
any solution for this??? - I Love Coding

1 Answers

0
votes

You are trying to re-use the same phone credential (you used it first to sign-in). The phone credential is one time use only. If you want to update email immediately after sign-in, re-auth is not needed. However, if you try to update email after some time, you will need to send a new SMS code to re-authenticate.