> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hightouch.com/llms.txt
> Use this file to discover all available pages before exploring further.

# iOS SDK

> Hightouch's iOS SDK for collecting events

The iOS SDK makes it easy to track events from Swift and Objective-C applications.

## Installation

The iOS SDK is hosted on GitHub at
`git@github.com:ht-sdks/events-sdk-swift.git` under the name
`events-sdk-swift`.

You may install the SDK by adding it to your `package.swift` file, or adding it
as a Package Dependency via Xcode.

## Initialization

You should initialize the SDK in a central location and store it in a variable
for use across your application. For example, you may want to initialize it in
your app delegate.

**Swift example**:

```
import Hightouch

let configuration = Configuration(writeKey: "YOUR_WRITE_KEY")
    .apiHost("us-east-1.hightouch-events.com/v1")

analytics = Analytics(configuration: configuration)
```

**Objective-C example**:

```
@import Hightouch

HTConfiguration *config = [[HTConfiguration alloc] initWithWriteKey:@"YOUR_WRITE_KEY"];
config.apiHost = "us-east-1.hightouch-events.com/v1";

analytics = [[HTAnalytics alloc] initWithConfiguration: config];
```

**Configuration options**:

| Option | Type | Description |
| - | - | - |
| `writeKey` | String | Your Highotuch write key. |
| `apiHost` | String | The API host to send the tracked events to. |
| `flushAt` | Int | The number of events to queue before sending events to the Hightouch API. Defaults to 20. |
| `flushInterval` | Int | The maximum amount of time (in seconds) to store events locally before forwarding to Hightouch. Defaults to 30 seconds. |
| `trackApplicationLifecycleEvents` | Bool | Whether to automatically track application lifecycle events (like opening the application). Defaults to `true`. |
| `foregroundSessionTimeout` | Int | Maximum foreground inactivity in milliseconds before a new session starts. Defaults to `1800000` (30 minutes). |
| `backgroundSessionTimeout` | Int | Maximum time in the background, in milliseconds, before a new session starts on resume. Defaults to `1800000` (30 minutes). |

## Prebuilt plugins

Use Hightouch's prebuilt plugins to add integrations without writing a plugin yourself. Optional plugins can require an additional package product or destination SDK.

### Braze

Use the Braze plugin to forward Hightouch calls to the Braze SDK on the device. This lets Braze evaluate in-app message triggers while the user is active, alongside normal event collection in Hightouch.

Use version `1.0.0` or later of `events-sdk-swift`. In Xcode, add the `HightouchBraze` product from the same package used for `Hightouch`. The plugin is distributed as Swift Package Manager source and uses the SDK's release versions. It brings in BrazeKit as a dependency.

After initializing your Hightouch client, register the destination with your Braze SDK API key and SDK endpoint:

```swift theme={null}
import HightouchBraze

let brazeDestination = BrazeDestination(
    apiKey: "YOUR_BRAZE_SDK_API_KEY",
    endpoint: "YOUR_BRAZE_SDK_ENDPOINT",
    options: .init(forwardScreenViews: true)
)
analytics.add(plugin: brazeDestination)
```

The plugin forwards `identify` calls as user updates and `track` calls as custom events. By default, `Order Completed` and `Completed Order` become purchases, with one purchase per product. Screen forwarding is off by default; `forwardScreenViews: true` forwards `screen` calls as custom events.

Your application configures message presentation, Content Cards, and push notifications. Add Braze's optional `BrazeUI` product to use its default UI, or connect your own presentation through `brazeDestination.onReady`. If your app already initializes Braze, use `BrazeDestination(braze: existingBraze)` to reuse that instance.

See the [Swift SDK installation notes](https://github.com/ht-sdks/events-sdk-swift#braze-destination) for platform and toolchain requirements and the [Braze example](https://github.com/ht-sdks/events-sdk-swift/tree/main/Examples/apps/BrazeExample) for UI setup. If you're replacing an mParticle kit, follow Migrate the mParticle Braze kit.

## Session tracking

Session tracking is enabled by default. The SDK attaches `sessionId`, `sessionStart`, and a `session` object to `context` on every event so you can group events from the same app session.

Sessions use two timeouts, both in milliseconds:

* `foregroundSessionTimeout` limits inactivity while the app is in the foreground.
* `backgroundSessionTimeout` limits how long the app can stay in the background before the next resume starts a new session.

Both default to `1800000` (30 minutes). Set both to `0` to disable session tracking.

A new session starts when any of these occur:

* First launch, when no session state is persisted.
* Foreground inactivity exceeds `foregroundSessionTimeout`.
* Resume after being backgrounded longer than `backgroundSessionTimeout`, including after process death.
* Calling `reset()`.

Session state is persisted across app relaunches. `sessionIndex` is a per-device lifetime counter. It starts at `0` and resets only when the app is uninstalled, not when you call `reset()`.

You can change the timeouts when you initialize the SDK:

**Swift example**:

```
let configuration = Configuration(writeKey: "YOUR_WRITE_KEY")
    .foregroundSessionTimeout(60 * 60 * 1000)
    .backgroundSessionTimeout(60 * 60 * 1000)
```

**Objective-C example**:

```
HTConfiguration *config = [[HTConfiguration alloc] initWithWriteKey:@"YOUR_WRITE_KEY"];
config.foregroundSessionTimeout = 60 * 60 * 1000;
config.backgroundSessionTimeout = 60 * 60 * 1000;
```

`context.session` includes:

| Field | Type | Description |
| - | - | - |
| `sessionId` | int | Current session ID (epoch milliseconds). |
| `sessionIndex` | int | Per-device lifetime counter. Starts at `0`. |
| `sessionStart` | boolean | Present and `true` only on the first event of the session. |
| `eventIndex` | int | 0-based index of the event within the session. |
| `previousSessionId` | int or null | Previous session ID. `null` on the first session. |
| `firstEventId` | UUID | `messageId` of the session's first event. |
| `firstEventTimestamp` | ISO 8601 | When the session began. |

`sessionId` and `sessionStart` are also set on `context` for parity with the [browser SDK](https://docs.hightouch.com/events/sdks/browser.md#session-tracking). `sessionStart` is included only when it is `true`.

## API

### Identify

The `identify` method sends an `identify` event. It accepts user id and trait
information for the current user -- if you only have partial information, you
can just supply a single parameter.

**Method signature**:

```
func identify<T: Codable>(userId: String, traits: T)
func identify<T: Codable>(traits: T)
func identify(userId: String)
```

**Method parameters**:

| Parameter | Type | Description |
| - | - | - |
| `userId` | String | The user's persistent ID |
| `traits` | Codable | Additional traits about the user, such as `email` and `name`. |

### Track

The `track` method sends a `track` event. The event name is required, and
additional properties that describe the event may be supplied.

**Method signature**:

```
func track(name: String)
func track<P: Codable>(name: String, properties: P?)
```

**Method parameters**:

| Parameter | Type | Description |
| - | - | - |
| `name` | String | The name of the event. |
| `properties` | Codable | Additional properties about the event, such as `product_id`. |

### Screen

The `screen` method sends a `screen` event. The screen title is required, and
additional information about the screen's category and properties may be
supplied.

**Method signature**:

```
func screen(title: String, category: String? = nil)
func screen<P: Codable>(title: String, category: String? = nil, properties: P?)
```

**Method parameters**:

| Parameter | Type | Description |
| - | - | - |
| `title` | String | The screen's name. For example "Getting started" |
| `category` | String | The screen's category. For example "Docs" |
| `properties` | Codable | Additional properties about the event, such as `from_link`. |

### Group

The `group` method sends a `group` event.

The id identifying the user's group is required. Additional traits on the group
can be provided.

**Method signature**:

```
func group(groupId: String)
func group<T: Codable>(groupId: String, traits: T?)
```

**Method parameters**:

| Parameter | Type | Description |
| - | - | - |
| `groupId` | String | The id for the group. |
| `traits` | Codable | Additional traits about the group, such as `company_name`. |

### Flush

The iOS SDK buffers events locally before sending them to Hightouch's servers.
This minimizes the number of requests made by the SDK and makes the tracking
non-blocking.

To force the local buffer to be sent to Hightouch immediately call the `flush`
method.

**Method signature**:

```
func flush()
```

### Reset

The `reset` method resets the `identify` and `group` for the local session.
Specifically, it resets the `anonymousId`, `userId`, `referrer`, and `traits`.

The `reset` method should be called when users log out. This way, if the user
logs back in with another account, the userIds and traits from the different
sessions remain separate. Calling `reset()` also starts a new analytics session.
See [Session tracking](#session-tracking).

**Method signature**:

```
func reset()
```
