首页 > 解决方案 > 使用电话验证凭据 iOS 更新电子邮件

问题描述

我正在创建一个使用PhoneAuth. 在我的应用程序中,我有一个功能可以让用户添加Email到他的帐户但并不意味着我使用电子邮件和密码对用户进行身份验证,我只想将电子邮件添加到他/她的帐户(auth.auth().currentUser)。

最初,我让用户在文本字段中添加他/她的电子邮件,然后我开始从他/她的设备中注销用户,reauthentication否则,我无法使用auth.updateEmail(). 但遗憾的是,在我调用 func 之后,凭证总是过期updateEmail()

这就是我登录用户和更新电子邮件的方式

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)

        }

    }

我不知道为什么凭证过期太快?我无法弄清楚如何使用 PhoneAuthCredential 更新用户电子邮件。有没有其他技术可以做到这一点?

标签: iosswiftfirebasefirebase-authentication

解决方案


您正在尝试重复使用相同的电话凭据(您首先使用它登录)。电话凭证只能使用一次。如果您想在登录后立即更新电子邮件,则不需要重新验证。但是,如果您在一段时间后尝试更新电子邮件,则需要发送新的 SMS 代码以重新进行身份验证。


推荐阅读