向Swift中的新Firebase用户发送电子邮件验证电子邮件

时间:2018-03-06 15:22:40

标签: swift firebase-authentication

我已将我的应用设置为使用电子邮件地址和密码成功登录或使用Firebase创建帐户。 我现在要做的是检查用户是否已经验证了他们的电子邮件,如果没有向他们发送Firebase允许我们编写的验证邮件。

@IBAction func createAccountTapped(_ sender: Any) {
    if let email = emailTextfield.text, let password = passwordTextfield.text {

        Auth.auth().createUser(withEmail: email, password: password, completion: { user, error in

            if let firebaseError = error {
                print(firebaseError.localizedDescription)
                return
            }



            self.presentTabBar()
        })
    }
}

@IBAction func loginTapped(_ sender: Any) {


    if let email = emailTextfield.text, let password = passwordTextfield.text {

        Auth.auth().signIn(withEmail: email, password: password, completion: {(user, error) in
            if let firebaseError = error {
                print(firebaseError.localizedDescription)
                return
            }
            self.presentTabBar()
        })
    }
}

这是我的“createaccount”和“login”功能。

我的问题是我不知道如何实现这个功能,以及在哪里调用这些功能。

您能告诉我发送此电子邮件的功能是什么,以及检查电子邮件是否经过验证的功能是什么?

1 个答案:

答案 0 :(得分:0)

您可以在创建帐户后立即发送验证邮件:

(不要忘记创建一个额外的按钮/操作,以便用户可以再次要求验证邮件)

private var authUser : User? {
    return Auth.auth().currentUser
}

public func sendVerificationMail() {
    if self.authUser != nil && !self.authUser!.isEmailVerified {
        self.authUser!.sendEmailVerification(completion: { (error) in
            // Notify the user that the mail has sent or couldn't because of an error.
        })
    }
    else {
        // Either the user is not available, or the user is already verified.
    }
}

结合您的代码:

@IBAction func createAccountTapped(_ sender: Any) {
    if let email = emailTextfield.text, let password = passwordTextfield.text {

        Auth.auth().createUser(withEmail: email, password: password, completion: { user, error in

            if let firebaseError = error {
                print(firebaseError.localizedDescription)
                return
            }

            sendVerificationMail()


            self.presentTabBar()
        })
    }
}

检查用户是否已验证:

@IBAction func loginTapped(_ sender: Any) {


    if let email = emailTextfield.text, let password = passwordTextfield.text {

        Auth.auth().signIn(withEmail: email, password: password, completion: {(user, error) in
            if let firebaseError = error {
                print(firebaseError.localizedDescription)
                return
            }

            if user != nil && !user!.isEmailVerified {
            // User is available, but their email is not verified.
            // Let the user know by an alert, preferably with an option to re-send the verification mail.
            }
            self.presentTabBar()
        })
    }
}