Skip to main content

Overview

Getting Started

The Magic class is the entry-point to the Magic SDK. It must be instantiated with a Magic publishable key.

Performance improvement (optional)

We use service workers for for better performance on web3 operations. If you’d like to take advantage of this performance boost, you’d have to enable app bound domains. To do that, add the following to your Info.plist and rebuild your app:
plist

Constructor

Magic()
ParameterTypeDefinition
apiKeyStringYour publishable API Key retrieved from the Magic Dashboard.
network?EthNetwork | CustomNodeConfiguration(EthNetwork): A representation of the connected Ethereum network (.mainnet or .goerli).

⁠(CustomNodeConfiguration): A custom Ethereum Node configuration with the following shape:

rpcUrl (String): A URL pointing to your custom Ethereum Node.

chainId? (Number): Some Node infrastructures require you to pass an explicit chain ID. If you are aware that your Node requires this configuration, pass it here as an integer.
locale?LocaleCustomize the language of Magic’s modal, email and confirmation screen. See Localization for more.

Initialization

In AppDelegate
Swift

Auth Module

The Auth Module and its members are accessible on the Magic SDK instance by the auth property.

loginWithSMS

Authenticate a user passwordlessly using a one-time code sent to the specified phone number. List of Currently Blocked Country Codes Arguments
  • configuration (LoginWithSMSConfiguration):
    • phoneNumber (string): The user phone number to log in with
    • showUI (boolean): If true, show an out-of-the-box pending UI while the request is in flight
Returns
  • Promise<string | null>: The promise resolves upon authentication request success and rejects with a specific error code if the request fails. The resolved value is a Decentralized ID token with a default 15-minute lifespan.
Example Closure
Swift
Promise
Swift

loginWithEmailOTP

Authenticate a user passwordlessly using an email one-time code sent to the specified user’s email address. Arguments
  • configuration (LoginWithEmailOTPConfiguration):
    • email (string): The user email to log in with
Returns
  • Promise<string | null>: The promise resolves upon authentication request success and rejects with a specific error code if the request fails. The resolved value is a Decentralized ID token with a default 15-minute lifespan.
Example Closure
Swift
Promise
Swift

Headless Email OTP (showUI: false)

If you’d rather build your own UI for the OTP, MFA, and device-verification prompts instead of using Magic’s out-of-the-box modal, pass showUI: false in LoginWithEmailOTPConfiguration. The SDK then returns a MagicEventPromise<String> instead of immediately resolving — subscribe to it for inbound events from the relayer, and emit outbound events (like the OTP the user typed) back to it. Arguments
  • configuration (LoginWithEmailOTPConfiguration):
    • email (string): The user email to log in with
    • showUI (boolean): Pass false to drive the flow with your own UI
  • eventLog (boolean): If true, logs each event received/emitted to the console
Returns
  • MagicEventPromise<String>: An event-driven promise. Call .on(eventName:) / .onPersistent(eventName:) to subscribe, .emit(eventType:arg:) to respond, and .done / .catch / .onError to handle the final result.
Events Events are grouped into four enums under AuthModule, mirroring the @magic-sdk/types design: LoginWithEmailOTPEventOnReceived — inbound email OTP events
CaseRaw valueMeaning
emailOTPSentemail-otp-sentOTP email was sent — prompt the user for the code
invalidEmailOTPinvalid-email-otpSubmitted OTP was invalid — may fire multiple times
expiredEmailOTPexpired-email-otpOTP expired
loginThrottledlogin-throttledToo many attempts — client should back off
maxAttemptsReachedmax-attempts-reachedNo retries left
LoginWithEmailOTPEventEmit — outbound email OTP events
CaseRaw valueMeaning
verifyEmailOTPverify-email-otpEmit with the OTP the user entered
cancelcancelEmit to cancel the in-progress login
MFAEventOnReceived — inbound MFA events (reusable across flows)
CaseRaw valueMeaning
mfaSentHandlemfa-sent-handleUser has MFA enabled — prompt for authenticator code
invalidMfaOTPinvalid-mfa-otpSubmitted MFA code was invalid — may fire multiple times
recoveryCodeSentHandlerecovery-code-sent-handlePrompt for MFA recovery code
invalidRecoveryCodeinvalid-recovery-codeSubmitted recovery code was invalid — may fire multiple times
recoveryCodeSuccessrecovery-code-successRecovery code accepted
MFAEventEmit — outbound MFA events (reusable across flows)
CaseRaw valueMeaning
verifyMFACodeverify-mfa-codeEmit with the authenticator code the user entered
verifyRecoveryCodeverify-recovery-codeEmit with the recovery code the user entered
lostDevicelost-deviceEmit to switch from MFA to recovery-code flow
cancelcancelEmit to cancel the in-progress MFA challenge
DeviceVerificationEventOnReceived — inbound device-verification events
CaseRaw valueMeaning
deviceNeedsApprovaldevice-needs-approvalNew device detected — user must approve via email
deviceVerificationEmailSentdevice-verification-email-sentDevice approval email was sent
deviceApproveddevice-approvedDevice was approved — login will continue
deviceVerificationLinkExpireddevice-verification-link-expiredDevice approval link expired
DeviceVerificationEventEmit — outbound device-verification events
CaseRaw valueMeaning
deviceRetrydevice-retryEmit to resend the device verification email
Use .on(eventName:) for events that fire once, and .onPersistent(eventName:) for events that may fire repeatedly (e.g. invalidEmailOTP on each wrong attempt) so the subscription isn’t torn down after the first occurrence. Example
Swift
Cancel an in-progress headless login at any time: emailOTPHandle?.emit(eventType: AuthModule.LoginWithEmailOTPEventEmit.cancel.rawValue).

Wallet Module

The Wallet Module and its members are accessible on the Magic SDK instance by the wallet property.

connectWithUI

Renders a simple login form UI to collect the user’s email address and authenticate them passwordlessly using a one-time passcode (OTP) sent to their email address they input. Arguments
  • None
Returns
  • A promiEvent which returns an String[] when resolved: An array of user accounts that are connected, with the first element being the current public address of the user. You can read more on PromiEvents here.
Example
Swift

showUI

Displays the fully navigable wallet to the user that adheres to the toggled configurations on your developer dashboard’s Widget UI tab. ⁠ ⁠This is only supported for users who login with email or Google. User must be signed in for this method to return or else it will throw an error. Arguments
  • None
Returns
  • Promise which resolves when the user closes the window
Example
Swift

User Module

The User Module and its members are accessible on the Magic SDK instance by the user property.

updateEmail

Initiates the update email flow that allows a user to change to a new email. Arguments
  • configuration (UpdateEmailConfiguration):
    • email (string): The user email to update with
    • showUI (boolean): If true, show an out-of-the-box pending UI while the request is in flight
Returns
  • Promise<Bool>: The promise resolves with a true boolean value if update email is successful and rejects with a specific error code if the request fails
Example
Swift

getIdToken

Generates a Decentralized Id Token which acts as a proof of authentication to resource servers. Arguments
  • configuration (GetIdTokenConfiguration):
    • lifespan (number): will set the lifespan of the generated token. Defaults to 900s (15 mins).
Returns
  • Promise<String>: Base64-encoded string representation of a JSON tuple representing [proof, claim]
Example
Swift

generateIdToken

Generates a Decentralized Id Token with optional serialized data. Arguments
  • configuration (GenerateIdTokenConfiguration):
    • lifespan (number): will set the lifespan of the generated token. Defaults to 900s (15 mins).
    • attachment (str): will set a signature of serialized data in the generated token. Defaults to "none".
Returns
  • Promise<String>: Base64-encoded string representation of a JSON tuple representing [proof, claim]
Example
Swift

getInfo

Retrieves information for the authenticated user. Arguments
  • None
Returns
  • Promise<UserInfo> - The issuer, email and cryptographic public address of the authenticated user.
    • issuer (string): The Decentralized ID of the user. In server-side use-cases, we recommend this value to be used as the user ID in your own tables.
    • email (string): Email address of the authenticated user
    • phoneNumber (string): Phone number of the authenticated user
    • publicAddress (string): The authenticated user’s public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
    • isMfaEnabled (boolean): A boolean indicating if user has multi-factor authentication enabled
    • recoveryFactors (RecoveryFactor):
      • value (string): Recovery value such as phone number
      • type (RecoveryMethodType): The method used for account recovery
Example
Swift

isLoggedIn

Checks if a user is currently logged in to the Magic SDK. Arguments
  • None
Returns
  • Promise<Bool>: A boolean value indicating if a user is logged in
Example
Swift

logout

Logs out the currently authenticated Magic user. Arguments
  • None
Returns
  • Promise<Bool>: A boolean value indicating if a user has been logged out
Example
Swift

showSettings

Displays an iframe with the current user’s settings. Allows for users to update their email address, enable multi-factor authentication, and add a recovery factor.
Access to MFA and account recovery require paid add-ons.
Arguments
  • None
Returns
  • Promise which resolves when the user closes the window
Example
Swift

updatePhoneNumber

Initiates the update phone number flow that allows a user to change their phone number. Arguments
  • configuration:
    • phoneNumber (str): The user phone number to update with
Returns
  • PromiEvent<boolean>: The promise resolves with a true boolean value if update email is successful and rejects with a specific error code if the request fails
Example
Swift

recoverAccount

Initiates the account recovery flow that allows a user to recover their account using their email address. Arguments
  • configuration (RecoverAccountConfiguration):
    • email (str): The user email address to recover account with
Returns
  • PromiEvent<boolean>: The promise resolves with a true boolean value if the account recovery is successful and rejects with a specific error code if the request fails
Example
Swift

Error Handling

There are three types of error class to be aware of when working with Magic’s iOS SDK:

Provider

Swift

Network

Swift

Events

Swift

Resources