iOS

Add Auth Service to Your iOS Project

Prerequisites

  • Install the following:

    • Xcode 14.1 or later

    • CocoaPods 1.12.1 or higher

  • Make sure that your project meets the following requirements:

    • Your project must target these platform versions or later:

      • iOS 14

  • Please note that the current version of our software does not support simulation testing. To perform testing, you will require an actual iPhone device.

Create a Particle Project and App

Before you can add our Auth Service to your iOS app, you need to create a Particle project to connect to your iOS app. Visit Particle Dashboard to learn more about Particle projects and apps.

👉 Sign up/log in and create your project now

Add the Auth Service SDK to Your App

Auth Service supports installation with CocoaPods.

Here's how to install the Auth Service using CocoaPods:

  1. Create a Podfile if you don't already have one. From the root of your project directory, run the following command:

pod init

2. To your Podfile, add the Auth Service pods that you want to use in your app:

pod 'ParticleAuthCore'
pod 'ParticleMPCCore'
pod 'Thresh'

3. Install the pods, then open your .xcworkspace file to see the project in Xcode:

pod install --repo-update
open your-project.xcworkspace

Edit Podfile

It is required for every iOS project that integrates the Auth Service SDK.

// paste there code into pod file
post_install do |installer|
installer.pods_project.targets.each do |target|
  target.build_configurations.each do |config|
  config.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES'
    end
  end
 end

Initialize Auth Service in your app

The final step is to add an initialization code to your application. You may have already done this as part of adding the Auth Service to your app.

  1. Create a ParticleNetwork-Info.plist into the root of your Xcode project

  2. Copy the following text into this file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>PROJECT_UUID</key>
	<string>YOUR_PROJECT_UUID</string>
	<key>PROJECT_CLIENT_KEY</key>
	<string>YOUR_PROJECT_CLIENT_KEY</string>
	<key>PROJECT_APP_UUID</key>
	<string>YOUR_PROJECT_APP_UUID</string>
</dict>
</plist>
  1. Replace YOUR_PROJECT_UUID, YOUR_PROJECT_CLIENT_KEY, and YOUR_PROJECT_APP_UUID with the new values created in your Dashboard

  2. Import the ParticleNetwork module in your UIApplicationDelegate

import ParticleNetworkBase 
  1. Initialize the ParticleNetwork service, which is typically in your app's application:didFinishLaunchingWithOptions: method:

// select a network from ChainInfo.
let chainInfo = ParticleNetwork.ChainInfo.ethereum
let devEnv = ParticleNetwork.DevEnvironment.debug
let config = ParticleNetworkConfiguration(chainInfo: chainInfo, devEnv: devEnv)
ParticleNetwork.initialize(config: config)
  1. Our SDK requires the 'Privacy - Face ID Usage Description' permission in order to function correctly. This is necessary because our SDK utilizes Face ID for secure user authentication. To request this permission, you must include the NSFaceIDUsageDescription key in your app's Info.plist file, accompanied by a string value explaining the reason for the request. The text you provide is presented to the user when your app first attempts to use Face ID. Here's an example:

<key>NSFaceIDUsageDescription</key>
<string>Your descriptive reason here...</string>

Together with Wallet Service

If you want to use with Wallet Service, you should add more pods in Podfile.

pod 'AuthCoreAdapter'

Initialize Particle Connect Service, add AuthCoreAdaper to your adapters.

API Reference

Get an AuthCore object

import ParticleAuthCore

let auth = Auth()

Get verification code

If you want to custom login page, add phone number or email login, here is the method to get the verification code

Prototype

func sendEmailCode(email: String) async throws -> Bool 
func sendPhoneCode(phone: String) async throws -> Bool

Parameters

  • email: Email address

  • phone: Phone number, format E164.

Returns

The function returns a bool value.

Example usage

Task {
    do {
        var result = try await self.auth.sendEmailCode(email: email)
        var result = try await self.auth.sendPhoneCode(phone: phone)
    } catch {
        print("send code failure, \(error)")
    }
}

Login

You can authenticate users in your app with an Auth object, by using the self.auth.connect function. This function supports different login types such as email, phone, Google, Apple, and Facebook. When the login is successful, a user wallet is created.

Prototype

func connect(
    type: LoginType, 
    account: String? = nil, 
    code: String? = nil, 
    socialLoginPrompt: SocialLoginPrompt? = nil) async throws -> UserInfo

Parameters

  • type: Specifies the login type (e.g., email, phone, jwt, google, apple, facebook).

  • account: Optional parameter for email, phone, or jwt login methods. You should pass in the user's email address, phone number, or jwt token here, the phone number must be in E164 format.

  • code: Optional parameter for email and phone, the verification code.

  • supportAuthType: Controls whether third-party login buttons are displayed. By default, all third-party login buttons are shown.

  • socialLoginPrompt: Social login prompt.

Returns

The function returns a user information object (userinfo) if the login is successful.

Example usage

// login with google
Task {
    do {
        let userInfo = try await self.auth.connect(type: LoginType.google, socialLoginPrompt: SocialLoginPrompt.selectAccount)
        self.handleUserInfo(userInfo)
    } catch {
        print("login failure, \(error)")
    }
}

// Login with email
Task {
    do {
        let userInfo = try await self.auth.connect(type: LoginType.email, account: "your email", code: "your verification code")
        self.handleUserInfo(userInfo)
    } catch {
        print("login failure, \(error)")
    }
}

We also keep the old method, one line code to login Particle with JWT.

let userInfo = try await auth.connect(jwt: jwt)

Account Abstraction could use together with Auth Core Service, explore Account Abstraction for more detail, learn how to get a smart account address, how to send transaction under AA mode.

Wallet Service could use together with Auth Core Service, explore Wallet Service for more detail, learn how to open wallet page, how to open send page, how to open swap page etc.

Present login page

Present a login page to help email and phone login, if you pass other login type, will bridge to connect method.

Prototype

func presentLoginPage(
    type: LoginType, 
    account: String?, 
    supportAuthType: [SupportAuthType] = [SupportAuthType.all], 
    socialLoginPrompt: SocialLoginPrompt? = nil, 
    config: LoginPageConfig?) async throws -> UserInfo

Parameters

  • type: Specifies the login type (e.g., email, phone, jwt, google, apple, facebook).

  • account: Optional parameter for email, phone, or jwt login methods. You should pass in the user's email address, phone number, or jwt token here, the phone number must be in E164 format.

  • supportAuthType: Controls whether third-party login buttons are displayed. By default, all third-party login buttons are shown.

  • socialLoginPrompt: Social login prompt.

  • config: LoginPageConfig, custom your icon, title and welcome message.

Returns

The function returns a user information object (userinfo) if the login is successful.

Example usage

Task {
    do {
        let userInfo = try await self.auth.presentLoginPage(type: LoginType.email, account: nil, config: nil)       
         self.handleUserInfo(userInfo)
    } catch {
        print("login failure, \(error)")
    }
}

Get user info

let userInfo = auth.getUserInfo()

Logout

The SDK will delete users' account information in cache.

let result = try await auth.disconnect()

Check user login status

let result = try await auth.isConnected()

Get Wallet Address

let evmAddress = auth.evm.getAddress()
let solanaAddress = auth.solana.getAddress()

Switch ChainInfo

let result = try await auth.switchChain(chainInfo: .bsc(.mainnet))

Signatures

Use Auth Core SDK to sign a transaction or message.

// personal sign
let result = try await auth.evm.personalSign(messageHex)
    
// personal sign unique
let result = try await auth.evm.personalSignUnique(messageHex)

// sign typed data
let result = try await auth.evm.signTypedData(typedDataV4)

// sign typed data unique
let result = try await auth.evm.signTypedDataUnique(typedDataV4)

// send evm transaction
let result = try await auth.evm.sendTransaction(transaction)

// request public rpc
let method = "eth_getBalance"
let parameters = ["your evm public address", "latest"]
let result = try await auth.evm.request(method: method, parameters: parameters)

Master Password

Wallet can set master password to protect assets.

// check user has master password or not
let result = try auth.hasMasterPassword()

// set or change master password
let result = try await auth.changeMasterPassword()

Payment Password

If set a payment password, user should input password before sign message and transaction.

// check user has payment password or not
let result = try auth.hasPaymentPassword()

Open account and security

Bind more login account, manage payment password etc.

try await auth.openAccountAndSecurity()

Set security account config

// set security account config, 
// promptSettingWhenSign default value is 1.
// promptMasterPasswordSettingWhenLogin default value is 0.
// 0 no prompt
// 1 first time show prompt
// 2 every time show prompt
// 3 force show prompt and user must set payment password or master password
 ParticleNetwork.setSecurityAccountConfig(
    SecurityAccountConfig(
        promptSettingWhenSign = 1,
        promptMasterPasswordSettingWhenLogin = 2
    )
)

Custom interface style

// this is the default setting
ParticleNetwork.setAppearence(.unspecified)
// dark 
ParticleNetwork.setAppearence(.dark)
// light
ParticleNetwork.setAppearence(.light)

Language setting

// Support en, ja, ko, zh_hans and zh_hant.
ParticleNetwork.setLanguage(.ja)
        
let language = ParticleNetwork.getLanguage()

Set custom UI json string

// Set custom ui is pass json string
let jsonString = "your custom ui json string, keys should be the same with customUIConfig.json in demo"
Auth.loadCustomUIJsonString(jsonString)

Blind sign enable

This switch will work if the following conditions are met:

1. your account is connected with JWT

2. your account does not set payment password

3. SecurityAccountConfig.promptSettingWhenSign is 0, you can call ParticleNetwork.setSecurityAccountConfig to update its value.

// set blind sign enable
Auth.setBlindEnable(true)
// get current blind sign enable state
let result = Auth.getBlindEnable()

Error

Try cast error into type ParticleNetwork.Response, you can check the information by printing its attributes.

Last updated