首页 > 解决方案 > SwiftUI、Firebase 链接以确认电子邮件

问题描述

我想增加在注册期间发送验证电子邮件的可能性。我如何在函数内部和 SignupView 中插入“sendEmailVerificationWithCompletion”?非常感谢 :)

import SwiftUI
import FirebaseAuth

// Add code here:
static func createUser(withEmail email:String, name: String, password:String, completionHandler:@escaping (Result<Bool,Error>) -> Void) {
    Auth.auth().createUser(withEmail: email, password: password) { (authResult, error) in
        if let err = error {
            completionHandler(.failure(err))
            return
        }
        guard let _ = authResult?.user else {
            completionHandler(.failure(error!))
            return
        }
        let data = FBUser.dataDict(uid: authResult!.user.uid, name: name, email: authResult!.user.email!)
        
        FBFirestore.mergeFBUser(data, uid: authResult!.user.uid) { (result) in
            completionHandler(result)
        }
        completionHandler(.success(true))
    }
}

//And add code here:
struct SignUpView: View {
    var body: some View {
        VStack(spacing: 20 ) {
            Button(action: {
                FBAuth.createUser(withEmail: self.user.email, name: self.user.fullname, password: self.user.password) { (result) in
                    switch result {
                    case .failure(let error):
                        self.errorString = error.localizedDescription
                        self.showError = true
                    case .success(_):
                        print("Account creation successful")
                    }
                }
            }) {
                Text("Register")
            }
        }
    }
}

标签: firebasegoogle-cloud-firestorefirebase-authenticationswiftui

解决方案


您可以在用户登录后随时告诉 Firebase 向当前用户发送验证电子邮件。例如,您可以在创建用户帐户后立即执行此操作:

Auth.auth().createUser(withEmail: email, password: password) { (authResult, error) in
    if let err = error {
        completionHandler(.failure(err))
        return
    }
    guard let _ = authResult?.user else {
        completionHandler(.failure(error!))
        return
    }

    // send verification email
    Auth.auth().currentUser?.sendEmailVerification { (error) in
      // ...
    }

    // write profile to database
    let data = FBUser.dataDict(uid: authResult!.user.uid, name: name, email: authResult!.user.email!)
    
    FBFirestore.mergeFBUser(data, uid: authResult!.user.uid) { (result) in
        completionHandler(result)
    }
    completionHandler(.success(true))
}

推荐阅读