Skip to content

Login with phone

To authenticate a user via their phone number, use the Privy client's email handler. This is a two step process:

  1. Send an OTP to the user provided phone number.
  2. Verify the OTP sent to the user.

1. Send an OTP to the user's phone number via SMS

After collecting and validating your users phone number, send an OTP by calling the sendCode method. Note: you must provide the phone number in E.164 format.

swift
let otpSentSuccessfully: Bool = await privy.sms.sendCode(to: "+14155552671")

if otpSentSuccessfully {
    // prompt user for OTP
} else {
    // handle unsuccessful attempt appropriately
    // OTP could fail if the network request fails
}

2. Authenticate with OTP

The user will then receive an SMS with a 6-digit OTP. Prompt for this OTP within your application, then authenticate the user with the loginWithCode method. Pass the following parameters to this method:

FieldTypeDescription
codeStringOTP code inputted by the user in your app.
sentToString?(Optional) The user's phone number. Though this parameter is optional, it is highly recommended that you pass the user's phone number explicitly.
swift
let authState = try await privy.sms.loginWithCode("123456", sentTo: "+14155552671")

if case .authenticated(_) = authState {
    // user authenticated!
}

Tracking login flow state

You can add provide a listener to receive state updates during the login with SMS process.

swift
privy.sms.setOtpFlowStateChangeCallback { otpFlowState in
    switch otpFlowState {
        case .initial:
            // Starting state
        case .sourceNotSpecified:
            // Phone number was not specified before calling "send code"
        case .sendCodeFailure(let error):
            // There was an error sending the code. Could be because of an
            // incorrectly formatted phone number or a network error
        case .sendingCode:
            // Sending code
        case .awaitingCodeInput:
            // The OTP was sent, now awaiting user input
        case .submittingCode:
            // Submitted code
        case .incorrectCode:
            // User typed in an incorrect code
        case .loginError(let error):
            // There was a network error while logging in.
        case .done:
            // OTP flow complete
    }
}