Swift:如何在创建新用户之前检查用户的电话号码是否已在Firebase数据库中

时间:2018-01-16 05:27:47

标签: swift firebase firebase-authentication

几个月前我刚开始使用Swift并帮助我更好地学习语言,我正在创建一个聊天应用程序。对于登录方法,我使用的是电话号码方式。我已经创建了入职流程,但我想实施一些东西,让我检查用户是否已经创建了一个具有该电话号码的帐户。如果有,我想将它们转换为主视图控制器,跳过入门视图控制器。

以下是我的电话验证查看控制器的代码(一个用于输入电话号码,另一个用于输入发送给用户手机的代码):

import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase

class PhoneVerification: UIViewController {

    //MARK: Properties
    @IBOutlet weak var phoneNumber: UITextField!
    @IBOutlet weak var code: UITextField!
    @IBOutlet weak var verifyCodeImage: UIButton!
    @IBOutlet weak var sendCodeImage: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    //MARK: Format phone text field
    var phoneFormatter = PhoneNumberFormatter()
    @IBAction func formatPhoneNumber(_ sender: UITextField) {
        sender.text = phoneFormatter.format(sender.text!, hash: sender.hash)
    }

    //MARK: When send secret code button is pressed

    @IBAction func sendCode(_ sender: Any) {
        let submitPhoneNumber = "+1" + phoneNumber.text!
        if submitPhoneNumber.count > 9{
        PhoneAuthProvider.provider().verifyPhoneNumber(submitPhoneNumber, uiDelegate: nil) {(verificationID, error) in
            if error != nil {
                print(error!)
            }else{
                UserDefaults.standard.set(verificationID, forKey: "authVerificationID")
                self.performSegue(withIdentifier: "phoneCode", sender: self)
            }
        }
        }else{
            let phoneNumAlert = UIAlertController(title: "Please enter your phone number", message: "You must enter your phone number to continue.", preferredStyle: .alert)

            phoneNumAlert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))

            self.present(phoneNumAlert, animated: true)
        }
    }
    let verificationID = UserDefaults.standard.string(forKey: "authVerificationID")

    //MARK: When verify code button is pressed
    @IBAction func verifyCode(_ sender: Any) {
        let credential = PhoneAuthProvider.provider().credential(
            withVerificationID: verificationID!,
            verificationCode: code.text!)

        //This is where the user is signed in if the verification code is correct
        Auth.auth().signIn(with: credential) { (user, error) in
            if let error = error {

                let invalidCodeAlert = UIAlertController(title: "That code is incorrect", message: "Please input the correct code", preferredStyle: .alert)

                invalidCodeAlert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))

                self.present(invalidCodeAlert, animated: true)
                print(error)
                return
            }
                //MARK: User is signed in
                print("Phone number: \(String(describing: user?.phoneNumber))")
                self.performSegue(withIdentifier: "accountCreated", sender: self)
        }
    }

}

非常感谢所有帮助!谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用 FirebaseAuthUI FirebasePhoneAuthUI 将您的手机号码注册到firebase中。它是Firebase本身提供的默认方法和用户界面。因此,您不必担心其他事情。

您只需使用pod安装PhoneAuthUI,并将以下代码记下到已注册的手机号码:

    FUIAuth.defaultAuthUI()?.delegate = self
    let phoneProvider = FUIPhoneAuth.init(authUI: FUIAuth.defaultAuthUI()!)
    FUIAuth.defaultAuthUI()?.providers = [phoneProvider]
    let currentlyVisibleController = self.navigationController?.visibleViewController
    phoneProvider.signIn(withPresenting: currentlyVisibleController!, phoneNumber: nil)

注册手机号码后,您将收到有关此方法的回调信息:

func authUI(_ authUI: FUIAuth, didSignInWith user: User?, error: Error?) {
    if user != nil{
        // here we need to check if current user is registered or not.
        var ref: DatabaseReference!
        ref = Database.database().reference()
        let userID = Auth.auth().currentUser?.uid
        }) { (error) in
            print(error.localizedDescription)
        }
    }else if error != nil{
        print(error?.localizedDescription)
    }
}

有关详细信息,请参阅this tutorial

答案 1 :(得分:0)

假设您将用户数据保存在users引用中。当用户登录时查看是否有任何数据,如果有,则它们是现有用户;如果没有,则它是新帐户:

Auth.auth().signIn(with: credential, completion: { [weak self](authDataResult, error) in

    if let error = error { return }

    guard let safeAuthDataResult = authDataResult else { return }

    // 1. get the signed in user's userId
    let userId = safeAuthDataResult.user.uid

    // 2. check to see if their userId exists at the user's path
    let usersRef = Database.database().reference().child("users").child(userId)
    usersPublicDataRef.observeSingleEvent(of: .value, with: { (snapshot) in

        // 3. this is a new user
        if !snapshot.exists() {

            // *** what you should do here is update the user's ref with some sort of data

        } else {

            // 4. this is an existing user
        }
    })
})