## Minimum requirements

Before getting started, check that your development environment meets the following requirements:

- iOS 15 or later
- Swift 5 or later
- Xcode 15.3 or later

## Installation

You can use either Swift Package Manager or CocoaPods to add the Digital Intelligence iOS SDK to your project, or you can manually download and install the framework. For more information, follow the instructions in the tabs below.

**Swift Package Manager**

To install the iOS SDK using Swift Package Manager, add the following package repository URL:

https://github.com/socure-inc/socure-sigmadevice-sdk-ios

**CocoaPods**

To install the iOS SDK using CocoaPods, add the following to your Podfile:

```ruby
use_frameworks!

pod 'SocureDeviceRisk'
```

Run `pod install` to install the dependencies.

**Manual install**

You can download the latest version of the SDK framework from [GitHub here](https://github.com/socure-inc/socure-sigmadevice-sdk-ios) and add it to your project. After you have successfully added the SDK to your project, you can import the SDK into your code by adding the `import DeviceRisk` statement.

## Configuration and usage

The Digital Intelligence iOS SDK's main class is `SigmaDevice`. At a high level the SDK provides the following methods to collect data to send it to the Socure backend:

- `initializeSDK()`
- `processDevice()`

### `initializeSDK()`

Prior to interacting with the Digital Intelligence iOS SDK, it must be initialized with `sdkKey` obtained from the **[Developer Workbench > SDK Keys](https://help.socure.com/riskos/docs/integration-guide-authentication#/)** page in RiskOS™.

The `initializeSDK()` function configures the SDK. It requires the `sdkKey`, an optional `SigmaDeviceOptions` and a `SigmaDeviceCallback`. It should preferably be called from the App's `application:didFinishLaunchingWithOptions:` delegate callback. For example:

```swift
func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    SigmaDevice.initializeSDK(<SDK KEY>, options: nil) { sessionToken, error in
        // Retrieve the sessionToken or handle any errors as appropriate
    }
    return true
}
```

The returned `sessionToken` can then be used on the respective device endpoints to fetch the data associated with the Session. Once retrieved, this `sessionToken` should be recorded by your application for use in the API requests associated with this transaction. The `sessionToken` will be passed in an API call in the `di_session_token` field.

#### `SigmaDeviceOptions`

These options can be passed into the `initializeSDK()` method to customize the SDK operation. It is represented as below:

```swift
struct SigmaDeviceOptions {
   var omitLocationData: Bool = false
   var advertisingID: String?
   var useSocureGov: Bool = false
   var configBaseUrl: String?
   var customerSessionId: String?
}
```

- `omitLocationData`: A boolean flag used to omit the location data from being sent as part of data collection. By default, it is set to `false`. When set to `true`, the location data will not be included during data collection regardless of the location permission given by the user.
- `advertisingID`: An optional string value that, when passed, will allow the advertising ID information to be sent as a part of data collection. Defaults to `null`.
- `useSocureGov`: A boolean flag used to configure the DeviceRisk SDK to communicate with the SocureGov backend. Defaults to `false`. This only applies to customers provisioned in the SocureGov environment. This flag is ignored if a `configBaseUrl` is provided.
- `configBaseUrl`: An optional string that configures the SDK to use a custom base URL for retrieving SDK configuration information.
- `customerSessionId`: An optional value that allows a customer provided identifier to be used in place of the SDK generated session token when calling Socure services.

#### `SigmaDeviceCallback`

`SigmaDeviceCallback` provides information about the status of the initialization call. The `initializeSDK()` call sets up data collection and returns the created `sessionToken`. The `sessionToken` can then be used on the respective device endpoints to fetch the data associated with the Session. Once retrieved, this `sessionToken` should be recorded by your application for use in the API requests associated with this transaction. The `sessionToken` will be passed in an API call in the `di_session_token` field.

```swift
typealias SigmaDeviceCallback = (SessionToken?, SigmaDeviceError?) -> Void
```

### `getSessionToken()`

This API lets the caller fetch the latest `sessionToken` generated by the SDK (including the one generated by `initializeSDK()`). The returned `sessionToken` can then be forwarded to the device endpoints to fetch the data associated with the Session:

```swift
do {
    let sessionToken = try await SigmaDevice.getSessionToken()
    print("Session Token is \(sessionToken)")
} catch {
    print("An error occurred")
}
```

### Error Handling

All SigmaDevice methods have the ability to return a `SigmaDeviceError` to let the user know when the SDK encounters an error. These errors are either thrown in the case of the `async throws` methods or via the `SigmaDeviceCallback`.

Below are the types of errors returned by the SDK:

```swift
enum SigmaDeviceError: Error {
    case dataFetchError
    case unknownError
    case networkConnectionError(Error)
    case dataUploadError(String?, String?)
    case sdkNotInitializedError
    case sdkPausedError
}
```

### Controlling Data Collection

By default the SDK will begin collecting data automatically. This includes data about the device and the way the user is interacting with the application. This data will be tracked as long as the application is in the foreground. Data collection is paused automatically when the application is backgrounded and automatically resumed when foregrounded.

In the event that further control over data collection is needed, two methods are supplied by the SDK:

- `SigmaDevice.pauseDataCollection()` - Will pause ongoing user behavior and interaction data collection. Data collection will not resume until `SigmaDevice.resumeDataCollection()` is called.
- `SigmaDevice.resumeDataCollection()` - Will resume data collection if collection was paused.

## Advanced Usage

### `processDevice()`

The `initializeSDK()` method automatically collects the data when initialized. Typically the data collected by `initializeSDK()` should be sufficient for most use cases. In cases where you need to explicitly invoke a data collection step, you can make use of `processDevice()`. Here we provide a `SigmaDeviceContext` to define the flow or screen within which the call occurs.

```swift
do {
    let sessionToken = try await SigmaDevice.processDevice(context: .homepage)
    print("Session Token is \(sessionToken)")
} catch {
   print("An error occurred")
}
```

#### `SigmaDeviceContext`

The following context values can be provided when calling `processDevice()`:

```swift
enum SigmaDeviceContext {
   case `default`
   case homepage
   case signup
   case login
   case profile
   case password
   case transaction
   case checkout
   case other(String)
}
```

Note the `initializeSDK()` call uses the `.default` value of `SigmaDeviceContext`.

## Silent Network Authentication

The Digital Intelligence iOS SDK provides the `performSilentNetworkAuth(mobileNumber:)` method to perform Silent Network Authentication using SIM-based verification. This allows you to verify device possession of a specified mobile number without requiring user interaction.

Silent Network Authentication is performed asynchronously. The result is not returned directly to the caller, but is made available for use within RiskOS™ decisioning workflows.

**Requirements:**

- The device must have an active SIM card and cellular data enabled.
- Devices on Wi-Fi will be automatically switched to cellular for authentication.
- Devices without cellular connectivity or with no SIM will not complete authentication, but this status is still reported for workflow decisioning.
- Your account must be provisioned for the `SilentNetworkAuth` feature.

**Usage Example:**

```swift
do {
    try await SigmaDevice.performSilentNetworkAuth(mobileNumber: "+12345678901")
    print("Silent Network Authentication initiated")
} catch {
    print("An error occurred")
}
```

The `mobileNumber` parameter should be provided in E.164 format (for example, "+12345678901").

> 📘
> **Note**:
> The Silent Network Authentication process is not complete until the asynchronous `performSilentNetworkAuth(...)` call returns.
> 📘
> **Note**:
> The result of the authentication is not returned directly. It is available for use in RiskOS™ workflows.
