---
name: coinme-risk-ios
description: "Add the Coinme Risk SDK to an iOS app: add the dependency, meet the App Store privacy and permission requirements, initialise the engine with the client ID, track inputs, and submit data before every transaction. Use when asked to add risk, fraud or device signals or the Coinme Risk Engine to an iOS, Swift or SwiftUI app."
metadata:
  surface: "caas"
  package: "CoinmeRisk · Swift"
  version: "1.1.2"
---

# Coinme Risk SDK on iOS

## When to use this skill

The human wants Coinme's Risk Engine in an iOS app, which Coinme requires before any transactional service is used from the app. The Widget SDK carries its own risk signals; this skill is for a partner's own app and its own transaction calls.

## Which integration this is

This skill is for the **Coinme-as-a-Service (CaaS) integration**: the partner keeps its own users and its own screens, and Coinme performs regulated services for them (onboarding and KYC, card vaulting, risk signals, transactions). The users are the partner's customers, not Coinme users. There is no Coinme Widget here, so no `rampId`, `partnerKey`, widget URL or embed allowlist. If the human wants to embed the Coinme Widget instead, this is the wrong skill: read [Two ways to build on Coinme](https://platformdocs.coinme.com/agents/surfaces.md) and pick a Widget skill.

## What you will produce

An iOS app that initialises the Risk Engine at launch with the client ID, tracks the inputs the guide names, gets a session tag right before each add-payment-method call and each order, and, where the SDK has a submit call, submits its data immediately before each transaction-initiating call to the backend, with the credentials kept out of source.

## Before you start: ask the human for these

The documentation does not contain them and you cannot derive them. Stop and ask, then continue. Never write a real value into a tracked file; keep each where the row says.

| Value | What it is | Where it goes |
| --- | --- | --- |
| `registry token` | Read-only token for the private registry that serves the Coinme SDKs. The install steps below read it from an environment variable they name; set that variable. | An environment variable or a gitignored registry config read at install time; CI reads it from a secret. Never in a committed file. |
| `clientId` | Identifies the integration to the Risk Engine; the SDK refuses to initialise without it. One per environment. Not a secret: it runs in the client, but the partner access token and client secret never go there with it. | Runtime configuration, not source; keep the development and production values apart. |
| `Partner ID (and Ramp ID for Ramp partners)` | Identifiers the session-tag call carries so the Risk Engine attributes the session: on the web the x-partner-id (and x-ramp-id) headers in getSessionTag additionalHeaders; on iOS, Android and React Native the partnerId (and rampId) options of getPartnerSessionTag. | Runtime configuration passed to the SDK; never hard-coded. |

## Rules for this skill

- Follow the steps in order and keep the code as written; change only identifiers the human gives you and the places marked as yours.
- Do not invent configuration fields, event names or API methods. What exists is what this skill shows plus what the installed package declares in its type definitions; check those before adding anything.
- Samples show the environment (such as `'sandbox'`, `'test'` or a staging base URL) as a literal so each stays self-contained. In the project, read it from the runtime configuration the human's build uses (for Vite, `VITE_*` variables in a gitignored `.env.local` with a committed `.env.example`), with a value per environment.
- This integration has no `rampId`, `partnerKey`, widget URL or embed allowlist. Do not ask for them or add them; they belong to the Widget skills. The one exception is the Risk SDK's optional `x-ramp-id` header, which only a Ramp partner sends.
- When a step needs a value you do not have, ask; do not substitute a placeholder that could ship.
- Read the linked pages when a step is unclear; they are the source this skill was generated from.

## Read first

Get the session tag right before each add-payment-method call and each order (getSessionTag on the web, getPartnerSessionTag on iOS, Android and React Native) and send it as webSessionId: a tag lives 30 minutes from when it was issued, using it doesn't extend that, and calling again while it is live returns the same tag. Never persist a tag across reloads or relaunches to reuse it. Pass the same device fingerprint to getPartnerSessionTag and as X-Device-Fingerprint on every other Coinme call for the user. Where the SDK has a submit call (submitCoinmeRiskData on React Native, CoinmeRiskEngine.submit on iOS and Android), make it immediately before every transaction-initiating server call. The guide's session-flow section is the contract.

Store listings and privacy disclosures in the guide are requirements, not suggestions; include them in what you hand back.

The Risk SDK takes no auth token from the app. In a partner app the session tag comes from the partner session-tag call (getPartnerSessionTag on iOS, Android and React Native; getSessionTag with the x-partner-id header on the web), which needs no token. Never pass the partner access token or a Transient Auth Token to the Risk SDK.

## Procedure

Follow the guide below in order. It is the integration guide for this platform as published, so the section names are the guide's own.

# Coinme Risk SDK for iOS Native Apps

## Introduction

The iOS Coinme Risk Engine SDK is a Swift library, distributed privately via Cloudsmith, that allows you to interact with the Coinme Risk Engine from your application. It provides utilities that allow you to integrate against the Coinme risk engine for the various transactional flows in your application so that Coinme may appropriately assess transactional risk when processing transactions.

> In order to utilize Coinme transactional services from within your application, you must implement and use the Coinme risk engine SDK.

**What is it?**

The Coinme risk engine aggregates data about user behavior for your application. It collects:

- Device data such as the type of device, OS name and version, etc.
- Location data such as where the user is connecting from.
- Connection data such as if the user is using a proxy or VPN, etc.
- Behavioral data such as how a user is interacting with your application, how quickly they are entering data into fields, use of clipboard functions, etc.

This data is used to determine the relative riskiness of the user / transaction.

> **Why is Risk Tagging Important?**
>
> Risk tagging allows the SDK to **track user interactions tied to specific actions within your application**. When an element is tagged, the risk engine can better assess **whether a user is behaving normally or if suspicious automation patterns are detected**.
>
> As an example, if the risk engine determines that the user location changes suddenly via a VPN to access a region restricted transaction type, then the engine may determine automation is at play and may **rank the transaction as high risk**.

## Implementing the iOS SDK

> **This package is not public**
>
> You will need an auth token in order to install it. You may obtain this by working with your Coinme integration contact.

### What You'll Need to Get Started

Before integrating the SDK, you will need the following credentials from your Coinme integration contact:

| Credential | Required For | Notes |
| --- | --- | --- |
| Cloudsmith auth token | Accessing the library | Required to access the private library in Cloudsmith |
| `clientId` | `RiskEngineSetupOptions` | Environment-specific — you will need one for development and one for production |
| `partnerId` | `getPartnerSessionTag()` | Passed via `GetPartnerSessionTagOptions`, this is your Partner identifier needed for integration with Coinme APIs |

> You will need two clientIds, one for your development builds and one for your prod builds; you may obtain these from your Coinme integration contact. It is very important that you pass the correct mode and clientId properties into the risk engine based on development or production usage, otherwise you may not stream your behavioral data to the correct environment, which can severely impact the risk engine’s ability to assess risk. This would ultimately negatively impact your transaction approvals.

### Installation

#### Set Your Entitlement Token

Create a `coinme.properties` file in your project root directory:

```properties
COINME_TOKEN=<YOUR_ENTITLEMENT_TOKEN>
```

Replace `<YOUR_ENTITLEMENT_TOKEN>` with the token provided by your Coinme integration contact. Do not commit this file to version control.

Important: Add `coinme.properties` to your `.gitignore` to keep your token secure:

`coinmme.properties`

```
coinme.properties
```

#### Add the SDK Repository and Dependency to your project - CocoaPods

Update your `Podfile`:

`CocoaPods Setup`

```swift
source 'https://github.com/CocoaPods/Specs.git'

# Read token from properties file
def read_token
  properties_file = File.join(File.dirname(__FILE__), 'coinme.properties')
  if File.exist?(properties_file)
    File.foreach(properties_file) do |line|
      key, value = line.split('=')
      return value.strip if key.strip == 'COINME_TOKEN'
    end
  end
  ENV['COINME_TOKEN'] || ''
end

token = read_token

plugin 'cocoapods-cloudsmith', {
  'source' => "https://packages.coinme.com/{COINME_TOKEN}/coinme-sdk-mobile/cocoapods/index.git"
}

target 'YourApp' do
  use_frameworks!
  pod 'CoinmeRiskSDK', '~> 1.1.2'
end
```

`Environment Variable Setup`

```swift
source 'https://github.com/CocoaPods/Specs.git'

token = ENV['COINME_TOKEN'] || ''

plugin 'cocoapods-cloudsmith', {
  'source' => "https://packages.coinme.com/{COINME_TOKEN}/coinme-sdk-mobile/cocoapods/index.git"
}

target 'YourApp' do
  use_frameworks!
  pod 'CoinmeRiskSDK', '~> 1.1.2'
end
```

If installing via an Environment Variable, you will also need to set the environment variable in your shell

```bash
export COINME_TOKEN=<YOUR_ENTITLEMENT_TOKEN>
```

#### Add the SDK Repository and Dependency to your project - Swift Package Manager

The SDK is also published to the Cloudsmith Swift Package Registry. Authenticate once with your entitlement token, then add the dependency.

Configure and log in to the registry (one-time):

```
swift package-registry set https://swift.cloudsmith.io/coinme/coinme-sdk-mobile/
swift package-registry login https://swift.cloudsmith.io/coinme/coinme-sdk-mobile/ --token YOUR_ENTITLEMENT_TOKEN
```

Next, add the dependency in your `Package.swift`:

```
dependencies: [
.package(id: "coinme.CoinmeRiskSDK", from: "1.1.2"),
]
```

Or in Xcode:

File > Add Package Dependencies… > Add from Registry and search for coinme.CoinmeRiskSDK.

The package bundles MobileIntelligence (SardineSDK) — no extra dependency is required.

### App Store Requirements

Before releasing your application with the Coinme Risk SDK, update your App Store Connect settings in your Apple developer portal.

#### App Privacy — Data Collection

In **App Store Connect > App Privacy**, declare the following:

1. **Data Collection:** Select **"Yes, we collect data from this app"**
2. **Location:**
  - Select **Coarse Location** and/or **Precise Location** (depending on your app settings)
  - Purpose: **App Functionality**
  - Reason: Required for fraud detection and prevention
3. **Identifiers — Device ID:**
  - Purpose: **App Functionality**
  - Check: **Yes, device ID is linked to user identity**

#### Privacy Policy

Update your App Store privacy policy to include the following disclosure:

> **Required Privacy Policy Language**
>
> For fraud protection purposes only, (1) we collect your Battery Usage, Device Identifier, Device Storage, and location information; (2) we also collect enough information to determine if you are trying to fake your current location by using a VPN or other location-spoofing tools.

### Required Permissions

Add location permissions to your `Info.plist`:

`Info.plist`

```swift
<dict>
  ...
  <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
  <string>We use your location to verify transactions and prevent fraud.</string>
  <key>NSLocationWhenInUseUsageDescription</key>
  <string>We use your location to verify transactions and prevent fraud.</string>
</dict>
```

This is a required permission for fraud detection and should be requested at runtime. Ensure your app handles the permission request appropriately for optimal risk assessment and to avoid issues from App Store Review.

### Implementation

Privacy & Compliance Notice

Important: If you use the Behavior Biometrics feature (enableBehaviourBiometrics = true), please ensure that your end users agree to your privacy policy before you begin collecting their Behavior Biometric data. This is required for compliance with privacy regulations.

#### Configuration Options

RiskEngineSetupOptions

| Option | Type | Required | Description |
| --- | --- | --- | --- |
| `mode` | `Mode` | Yes | Used to point to environment `.Test` or `.Prod` |
| `clientId` | `String` | Yes | Your environment-specific Client ID |
| `partnerId` | `String?` | No | Partner Identifier |
| `customerId` | `String?` | No | Customer/User's identifier |
| `sessionKey` | `String?` | No | Session key (automatically generated if not provided) |
| `flow` | `FlowType?` | No | Current User flow (Onboarding, CardTransaction, or CardLinking) |
| `region` | `AppRegion` | No | Your app's region of service (`.default` (US), `.ca`, `.eu`, `.au`, `.in`) |
| `enableBehaviourBiometrics` | `Bool` | No | Enabled behavior tracking (default: true) |
| `enableClipboardTracking` | `Bool` | No | Enable clipboard tracking (default: false) |
| `enableFieldTracking` | `Bool` | No | Enable automatic field tracking (default: true) |
| `setCloudEntitlements` | `Bool` | No | Enable iCloud feature (default: false, requires additional setup) |

#### FlowType Options

- `FlowType.Onboarding` - New user registration flow
- `FlowType.CardTransaction` - Payment/card transaction flow
- `FlowType.CardLinking` - Adding payment methods flow

#### sessionKey

The `sessionKey` is a unique identifier for tracking a specific user session.

Once a key is provided for the set up, it will be cached for the duration of the app's active session. If no value is provided, the key will be automatically generated.

You will want to invoke `.getPartnerSessionTag()` to get an updated value that our backend will use to associate collected user data and risk score. Failure to call this and get the expected session key value may result in loss of data for accurate risk assessment. Call it right before each add-payment-method call and each order: a session tag lives 30 minutes from when it was issued, and using it doesn't extend that.

Using `.updateCoinmeRiskEngine()` with a new key will override and update the cached value.

To clear a `sessionKey`, you may call `.resetStoredSessionKey()`

> When you call `getPartnerSessionTag()`, the returned `webSessionID` automatically becomes the active session key. All subsequent calls to `updateCoinmeRiskEngine()` will use this session key unless you explicitly provide a different one.

#### getPartnerSessionTag()

Retrieve the session tag from the backend API. The resulting `webSessionID` is automatically used to update the `CoinmeRiskEngine` configuration.

```swift
try await CoinmeRiskEngine.getPartnerSessionTag(options: GetPartnerSessionTagOptions) -> SessionTagData
```

Parameters of `GetPartnerSessionTagOptions`. The SDK sends them as request headers and a query parameter, to the host your `mode` selects:

| Param | Type | Required | Description |
| --- | --- | --- | --- |
| `partnerId` | `String` | Yes | Your partner identifier, sent as the `partnerId` header |
| `accountId` | `String` | Yes | The customer ID, sent as the `accountId` query parameter |
| `fingerprint` | `String` | Yes | The device fingerprint, sent as the `X-Device-Fingerprint` header |
| `rampId` | `String?` | No | Your Ramp ID, sent as the `X-ramp-id` header (Ramp partners only) |
| `additionalHeaders` | `[String: String]` | No | Additional headers that may be included if needed by the backend |
| `timeout` | `Int` | No | Request timeout in milliseconds (default: 10000) |

#### Initialize the SDK

Initialize the Risk Engine in your app's initialization:

```swift
import CoinmeRiskSDK

let options = RiskEngineSetupOptions(
    mode: .Prod,  // Use .Test for testing
    clientId: "your-client-id",
    enableBehaviourBiometrics: true,
    enableFieldTracking: false  // Set to false for manual tracking
)

CoinmeRiskEngine.setupCoinmeRiskEngine(options: options)
```

#### Update the SDK

You can update the configuration with flow, sessionKey and customerId options:

```swift
CoinmeRiskEngine.updateCoinmeRiskEngine(
    RiskEngineUpdateOptions(
        sessionKey: "new-session-key",
        flow: .cardTransaction,
        customerId: "customer-id"
  )
)
```

#### Submit Data Before Transactions

Submits all collected behavioral and device date to the backend for risk assessment. Use callback version to ensure data is submitted before making subsequent API calls.

```swift
CoinmeRiskEngine.submit(
    onSuccess: {
        // Data successfully submitted - safe to proceed with transaction API call
        processPayment()
    },
    onError: { error in
        print("Risk SDK submission failed: \(error)")
        handleError(error)
    }
)
```

#### What it collects:

- Sensor data (motion, orientation, pressure)
- Behavioral biometrics (typing patterns, interaction timing)
- Device context (clipboard activity, focus patterns)
- Page/screen engagement metrics

#### When to call:

- Before payment/transaction API calls
- Before critical actions (login, signup, money transfer)
- After form completion or user interaction flow

#### Other Utility Methods

#### Get Current Config

Returns the current runtime configuration.

```swift
CoinmeRiskEngine.getCoinmeRiskEngineConfig() -> RiskEngineUpdateOptions
```

#### Reset Session

Resets the stored session key.

```swift
CoinmeRiskEngine.resetStoredSessionKey()
```

#### Reset SDK

Clears the singleton instance and cleans up resources.

```swift
CoinmeRiskEngine.reset()
```

#### Manual Input Field Tracking

> If you choose to manually track input fields, first disabled automatic field tracking in the configuration. This can be done by ensuring `enableFieldTracking = false` when you set options for the `CoinmeRiskEngine`.

How to set up custom `TextField` for tracking:

`SwiftUI`

```swift
import SwiftUI
import CoinmeRiskSDK

struct LoginView: View {
    @State private var email = ""
    @FocusState private var isEmailFocused: Bool

    var body: some View {
        TextField("Email", text: $email)
            .focused($isEmailFocused)
            .onChange(of: email) { newValue in
                CoinmeRiskEngine.trackTextChange(viewId: "email", text: newValue)
            }
            .onChange(of: isEmailFocused) { isFocused in
                CoinmeRiskEngine.trackFocusChange(viewId: "email", isFocus: isFocused)
            }
    }
}
```

`UIKit`

```swift
// In your UIViewController
class LoginViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var emailTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        emailTextField.delegate = self
    }

    // UITextFieldDelegate - Track focus changes
    func textFieldDidBeginEditing(_ textField: UITextField) {
        CoinmeRiskEngine.trackFocusChange(viewId: "email", isFocus: true)
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        CoinmeRiskEngine.trackFocusChange(viewId: "email", isFocus: false)
    }

    // UITextFieldDelegate - Track text changes
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
        let currentText = textField.text ?? ""
        let newText = (currentText as NSString).replacingCharacters(in: range, with: string)
        CoinmeRiskEngine.trackTextChange(viewId: "email", text: newText)
        return true
    }
}
```

Be descriptive when assigning a value for `viewId` ("email", "password", "debitCardNumber", etc)

#### Tracking Methods

Track text changes to an input field

```swift
CoinmeRiskEngine.trackTextChange(viewId: String, text: String)
```

Track focus change to a field

```swift
CoinmeRiskEngine.trackFocusChange(viewId: String, isFocus: Bool)
```

Note: Be sure to use the same `viewId` for both `trackTextChange()` and `trackFocusChange()` if they are used to reference the same text field or other custom UI component.

#### Optional Features

#### Enable Location Service

Initialize Apple's LocationManager to provide live location updates:

```swift
import CoreLocation

class LocationService: NSObject, CLLocationManagerDelegate {
    let locationManager: CLLocationManager?

    override init() {
        locationManager = CLLocationManager()
        locationManager?.requestWhenInUseAuthorization()

        super.init()

        locationManager?.delegate = self
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
            if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
                if CLLocationManager.isRangingAvailable() {
                    let latitude = manager.location?.coordinate.latitude
                    let longitude = manager.location?.coordinate.longitude

                    print("Location: \(latitude ?? 0), \(longitude ?? 0)")
                }
            }
        }
    }
}
```

#### Enable Wi-Fi Information Tracking

Wi-Fi BSSID and SSID can provide additional location signals.

1. Enable Location Services (required)
2. In Xcode:
  - Go to your target scheme
  - Click **Signing & Capabilities**
  - Click **+ Capability**
  - Add **Access WiFi Information**

#### Enable iCloud Record ID

iCloud Record ID remains consistent across devices that are associated with the same Apple account.

1. In Xcode
2. Set the flag in the SDK configuration:

> DO NOT set `setCloudEntitlements` to true unless CloudKit is properly configured, or the SDK will crash.

#### Enable Biometric Authentication Detection

Detect the use of FaceID and TouchID

Update your `Info.plist`

```
<dict>
  ...
  <key>NSFaceIDUsageDescription</key>
  <string>Face ID is used to verify your identity.</string>
</dict>
```

## Verify

Build and run the app. Confirm the Risk Engine initialises without an error, that a session tag is obtained with the headers the guide names right before each add-payment-method call and each order, that the submit call (where the SDK has one) completes right before a transaction call, and that no client ID or token is in a committed file. Hand back the privacy and store-listing items the guide requires.

### Reading the result

**Done when:** Setup completes and a session tag comes back for the customer on this device.

**Stop and ask the human when** the client ID is refused, or the partner is unknown (`143-404-317-704`).

Judge every Coinme call by its body, not its HTTP status: a refused request usually comes back as HTTP 200 with the error in the body. [Reading results](https://platformdocs.coinme.com/agents/results.md) has the rule, what each common error code asks you to do, and what to send your Coinme integration contact when something fails.

## Reference
- [Coinme Risk SDK](https://platformdocs.coinme.com/docs/coinme-risk-sdk.md)
- [Coinme Risk SDK for iOS Native Apps](https://platformdocs.coinme.com/docs/risk-sdk-for-ios-native-apps.md)
- [Build: the Library of SDKs and documents](https://platformdocs.coinme.com/pages/build/library.md)
