# iOS SDK quick start

This guide describes how to quickly integrate Fraud Prevention into your iOS application to get started. This includes both the client-side integration using the [iOS SDK](https://transmitsecurity.github.io/accountprotection-ios-sdk-docs/documentation/accountprotection/#Overview), as well as the backend API integration required to complete the flow.

Check out our sample app 

Note
Client-side integrations are recommended for POCs and testing. For production environments, consider implementing [Backend integration](/guides/risk/quick_start_backendapi). Learn more about integration options: [Client-side integration vs Backend integration](/guides/risk/integration_clientside_vs_backend).

## How it works

The flow starts with the user navigating to the iOS app (1). The SDK gets initialized and starts sending telemetry to Mosaic (2). When a user performs an action, for example, clicks a login button (3), the SDK triggers an action event (4) and obtains an action token (5) which then forwards to the backend (6). Having received an action token, the application backend uses it to fetch recommendation from Mosaic (7 & 8) and instructs the client to act accordingly (9) in order to complete the login procedure (10). Upon successful login, the client sets the user (11).

![](/assets/drs-integrations.88751400966c093ef32f43c3a699d31f766f7ff46b9053f2fbaa898cf39860b5.e95a590b.png)

## Requirements

- iOS 13+
- Xcode 11+


## Step 1: Get client credentials

div
div
Admin Portal
Client credentials are used to identify your app and generate access tokens for authorizing Mosaic requests. To obtain them, you'll need to create an application in the [Admin Portal](https://portal.transmitsecurity.io/) (if you don’t have one yet).

1. From **Applications**, click **Add application**.
2. Add the friendly application name to display in the Admin Portal.
3. Add an OIDC client, specify the client secret as an authentication method, and your website URL as a redirect URI (e.g., `https://your-domain.com`).


Note
These fields are required for all Mosaic apps, but won’t be used for Fraud Prevention.

1. Click **Add** to create your application. This will automatically generate your client credentials.


## Step 2: Add SDK to project

div
div
Client
Add the SDK to your project so your application can access all the Fraud Prevention functionality. To do this, install the SDK as a dependency using Swift Package Manager:


```swift
dependencies: [
    .package(url: "https://github.com/TransmitSecurity/accountprotection-ios-sdk.git", .upToNextMajor(from: "2.0.0"))
]
```

## Step 3: Initialize SDK

div
div
Client
Start monitoring your end-user risk levels by initializing and configuring the SDK.

details
summary
b
Initialize using PLIST configuration (recommended)
To do this, create a plist file named `TransmitSecurity.plist` in your Application with the following content. The `[CLIENT_ID]` should be replaced with your client ID from step 1.


```xml
<?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>credentials</key>
	<dict>
		<key>baseUrl</key>
		<string>https://api.transmitsecurity.io/</string>
		<key>clientId</key>
		<string>[CLIENT_ID]</string>
	</dict>
</dict>
</plist>
```

Add the code below to your Application Class

Note
- Make sure to add the `import AccountProtection` at the top of the implementation class.
- The SDK can be configured to work with an EU or Canada cluster by setting the `baseUrl` key within the TransmitSecurity.plist to `https://api.eu.transmitsecurity.io/` (EU) or `https://api.ca.transmitsecurity.io/` (Canada).


UIKit

```swift
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        TSAccountProtection.initializeSDK()
        return true
    }
}
```

SwiftUI

```swift
struct ExampleApp: App {

    init() {
        TSAccountProtection.initializeSDK()
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
```

details
summary
b
Initialize using SDK parameters
Add the code below to your Application Class. The `[CLIENT_ID]` should be replaced with your client ID from step 1.

Note
- Make sure to add the `import AccountProtection` at the top of the implementation class.
- The SDK can be configured to work with a different cluster by setting the first initialization parameter to `baseUrl : 'https://api.eu.transmitsecurity.io/'` for EU, `baseUrl : 'https://api.ca.transmitsecurity.io/'` for Canada, or `baseUrl : 'https://api.au.transmitsecurity.io/'` for Australia, or specify a [custom domain](/guides/deployment/custom_domains) if you use one.


UIKit

```swift
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        TSAccountProtection.initialize(clientId: [CLIENT_ID])
        return true
    }
}
```

SwiftUI

```swift
struct ExampleApp: App {

    init() {
        TSAccountProtection.initialize(clientId: [CLIENT_ID])
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
```

SDK session
Start an SDK session and obtain a device session token after SDK initialization and prior to triggering events, and persist it on your backend. This step is optional for client-side integration but **strongly recommended** as it allows to transition to the [backend integration](/guides/risk/quick_start_backendapi)—a device session token is needed to trigger events from the backend and binds user's interactions to their device.


```swift
TSAccountProtection.getSessionToken { token in
    debugPrint("[DEBUG]: device session token: \(token)")
}
```

## Step 4: Trigger actions

div
div
Client
To obtain risk recommendations for sensitive actions, your application should report these actions using the SDK. To do this, add the code below to relevant user interactions (e.g., the Login button `click` event handler). Replace `[ACTION_TYPE]` with the appropriate action type from our [list of actions](/guides/risk/recommendations#action-types). `ActionEventOptions` and `TransactionData` objects are optional and could be set to null.

To improve Fraud Prevention, optionally pass the correlation ID, and claimed user ID and its type (for users that haven't authenticated yet). This call returns  `actionToken`, make sure to pass it to your backend to obtain the recommendation in the next step.

To report precise device location, add `locationConfig` to the call (the user has to consent to sharing location in advance, see [Track geolocation](/guides/risk/report_geolocation)).

Note
`customAttributes` is an optional object which add context to an action but must match the schema defined in the Portal. Invalid attributes are ignored (see [Custom Attributes](/guides/risk/action-attributes))

For an alternative approach that directly utilizes our backend API, refer to our [Backend API implementation](/guides/risk/quick_start_backendapi#step-4-trigger-actions) guide.


```swift
// Add `import AccountProtection` on top of the implementation class
// Transaction data (optional, pass 'nil' if not used)
let payer = TSTransactionData.Payer(name: "PAYER_NAME",
                                    bankIdentifier: "PAYER_BANK_IDENTIFIER",
                                    branchIdentifier: "PAYER_BRANCH_IDENTIFIER",
                                    accountNumber: "PAYER_ACCOUNT_NUMBER")

let payee = TSTransactionData.Payee(name: "PAYEE_NAME",
                                    bankIdentifier: "PAYEE_BANK_IDENTIFIER",
                                    branchIdentifier: "PAYEE_BRANCH_IDENTIFIER",
                                    accountNumber: "PAYEE_ACCOUNT_NUMBER")

let transactionData = TSTransactionData(amount: "AMOUNT",
                                        currency: "CURRENCY",
                                        reason: "REASON",
                                        transactionDate: "TRANSACTION_DATE",
                                        payer: payer,
                                        payee: payee)

// Options (optional, pass 'nil' if not used)
let options = TSActionEventOptions(correlationId:"CORRELATION_ID",
                                  claimUserId: "CLAIM_USER_ID",
                                  referenceUserId: "REFERENCE_USER_ID",
                                  transactionData: transactionData)

// Optional, pass 'nil' if not used
let customAttributes: [String: Any]? = [
    "accountAgeInDays": 12,
    "customerSegment": "VIP",
    "hasCompletedKYC": true
]

/* Optional, can be one of the following modes:
* default: falls back to default configuration
* disabled: doesn't report location
* forceCurrent: real-time retrieval
* forceLastKnown: reports the last captured location
* lastKnown(validFor: int) reports last known location if captured within last X minites
*/
let collectionMode: TSLocationCollectionMode = .lastKnown(validFor: 30)

TSAccountProtection.triggerAction(ACTION_TYPE, customAttributes: customAttributes, options: options, locationConfig: .init(mode: collectionMode)) { result in
    DispatchQueue.main.async {
        switch result {
          case .success(let response):
            let actionToken: String = response.actionToken
          case .failure(let error):
            switch error {
              case .disabled:
                break
              case .connectionError:
                break
              case .internalError:
                break
              case .notSupportedActionError:
                break
              @unknown default:
                break
            }
        }
    }
}
```

## Step 5: Fetch recommendation

div
div
Backend
You can fetch recommendations from your **backend** for the reported action using the [Recommendation API](/openapi/risk/recommendations.openapi/other/getriskrecommendation). This is the same API that's also used for web integrations.

Mosaic APIs are authorized using an OAuth access token so you'll need to fetch a token using your client credentials (from step 1). To do this, send the following request:


```js
  const { access_token } = await fetch(
    `https://api.transmitsecurity.io/oidc/token`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
      body: new URLSearchParams({
        grant_type: client_credentials,
        client_id: [CLIENT_ID],
        client_secret: [CLIENT_SECRET]
      })
    }
  );
```

From your backend, invoke the Recommendation API by sending a request like the one below. The `[ACCESS_TOKEN]` is the authorization token you obtained using your client credentials and `[ACTION_TOKEN]` is the `actionToken` received from the SDK in Step 4.


```js
const query = new URLSearchParams({
  action_token: '[ACTION_TOKEN]',
}).toString();

const resp = await fetch(
  `https://api.transmitsecurity.io/risk/v1/recommendation?${query}`,
  {
    method: 'GET',
    headers: {
      Authorization: 'Bearer [ACCESS_TOKEN]',
    },
  }
);
```

## Step 6: Set user

div
div
Client
A user identifier must be reported to Mosaic after you've fully authenticated the user (including, for example, any required 2FA that was done). This will set the user for all subsequent events in the current device session, or until the app prompts the user to re-login, or until the user is explicitly cleared.

To do this, add the code below after your application has authenticated a user (or after SDK initialization if you already have the user context for the authenticated user). The `[USER_ID]` is an opaque identifier for the user in your system and must not include personal user identifiers, such as email, in plain text.

Note
Make sure to add the `import AccountProtection` at the top of the implementation class.


```swift
TSAccountProtection.setUserId([USER_ID])
```

Note
For an alternative approach that directly utilizes our backend API instead, refer to our [Backend API implementation](/guides/risk/quick_start_backendapi#step-6-report-action-result) guide.

## Step 7: Clear user

div
div
Client
The user gets automatically cleared once the device session expires or in case of a new login action. After the user logs out, you should clear the set user so they are not associated with future actions. To clear the user, call the `clearUser()` method as shown below.

Note
Make sure to add the `import AccountProtection` at the top of the implementation class.


```swift
TSAccountProtection.clearUser()
```