Skip to content

Login with email

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

  1. Send an OTP to the user provided email address.
  2. Verify the OTP sent to the user.

1. Send an OTP to the user's email address

After collecting and validating your users email, send an OTP by calling the sendCode method.

swift
let otpSentSuccessfully: Bool = await privy.email.sendCode(to: "[email protected]")

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 email with a 6-digit OTP. Prompt for this OTP within your application, then authenticate the user with the loginWithCode method. As a parameter to this method, pass an object with the following fields:

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

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

Tracking login flow state

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

swift
privy.email.setOtpFlowStateChangeCallback { otpFlowState in
    switch otpFlowState {

    case .initial:
        // Starting state
    case .sourceNotSpecified:
        // Email 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 email 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
    }
}