use firebase products to create a signup process using a phone number in swift

To create a signup process using a phone number with Firebase Authentication in Swift, follow these steps:

  1. Import Firebase Authentication in your Swift file:
main.swift
import Firebase
16 chars
2 lines
  1. Create an IBOutlet for a text field where the user will enter their phone number.
main.swift
@IBOutlet weak var phoneNumberField: UITextField!
50 chars
2 lines
  1. In your button action method, retrieve the phone number entered by the user and use the PhoneAuthProvider class to initiate the phone number verification process:
main.swift
@IBAction func signupButtonTapped(_ sender: Any) {
    guard let phoneNumber = phoneNumberField.text else { return }

    PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            return
        }

        // Save the verificationID somewhere so you can use it in the next step
        UserDefaults.standard.set(verificationID, forKey: "authVerificationID")

        // Show the verification screen to the user
        // This is a custom view controller that you need to create yourself
        let verificationViewController = VerificationViewController()
        self.present(verificationViewController, animated: true, completion: nil)
    }
}
797 chars
19 lines
  1. When the user enters the verification code sent to their phone, use the PhoneAuthProvider class to create a Credential object and sign in the user with Firebase Authentication:
main.swift
func signInWithPhoneNumber(_ verificationCode: String) {
    guard let verificationID = UserDefaults.standard.string(forKey: "authVerificationID") else { return }

    let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID, verificationCode: verificationCode)

    Auth.auth().signIn(with: credential) { (authResult, error) in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            return
        }

        // User is signed in
        print("User signed in")
    }
}
552 chars
16 lines

That's it! You can now use Firebase Authentication to allow users to sign up and sign in with their phone number in your Swift app.

gistlibby LogSnag