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

# iOS SDK

> Install and configure the Userpilot iOS SDK

Install and initialize the Userpilot iOS SDK, identify users, track screens and events, and configure optional settings.

The Userpilot iOS SDK enables you to capture user insights and deliver personalized in-app experiences in real time. With a one-time setup, you can immediately begin leveraging Userpilot's analytics and engagement features to understand user behavior and guide their journeys in-app.

***

## Getting Started

Before you begin, ensure your iOS project meets the following requirements:

* **iOS Deployment Target:** 13 or higher.
* **Xcode:** Version 15 or higher.

## Installing the Library

### CocoaPods

1. Add the Userpilot dependency to your `Podfile`. Replace `<SDK_VERSION>` with the latest version available from [CocoaPods](https://cocoapods.org/pods/Userpilot).

```ruby theme={null}
target 'YourTargetName' do
  pod 'Userpilot', '~><SDK_VERSION>'
end
```

2. Run `pod install` in your project directory.

### Swift Package Manager

1. In Xcode, navigate to **File -> Add Packages**.
2. Enter the package URL: `https://github.com/Userpilot/ios-sdk`.
3. For **Dependency Rule**, select **Up to Next Major Version**.
4. Click **Add Package**.

Once integrated, the Userpilot SDK is available throughout your application.

## Initialize the SDK

Initialize Userpilot once in your App Delegate or Scene Delegate during app launch to ensure the SDK is ready as soon as your app starts. Replace `<APP_TOKEN>` with your Application Token from the [Environments Page](https://run.userpilot.io/environment).

<CodeGroup>
  ```swift Swift theme={null}
  @main
  class AppDelegate: UIResponder, UIApplicationDelegate {
      var userpilot: Userpilot?

      func application(_ application: UIApplication,
                       didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
          userpilot = Userpilot(config: Userpilot.Config(token: "<APP_TOKEN>")
              .logging(true) // Enable or disable logging
          )  
          return true
      }
  }
  ```

  ```c Obj-c theme={null}
  #import "Userpilot-Swift.h"

  @interface AppDelegate : UIResponder <UIApplicationDelegate>

  @property (strong, nonatomic) Userpilot *userpilot;

  @end

  @implementation AppDelegate

  - (BOOL)application:(UIApplication *)application
      didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

      Config *config = [[Config alloc] initWithToken:@"<APP_TOKEN>"];
      [config loggingWithEnabled:YES]; // Enable or disable logging

      self.userpilot = [[Userpilot alloc] initWithConfig:config];

      return YES;
  }

  @end
  ```
</CodeGroup>

## Identify Users (Required)

Identify unique users and companies (groups of users) alongside their properties. Once identified, all subsequent tracked events and screens will be attributed to that user.

<Warning>
  **Important**

  It's crucial to call the Userpilot identify function; without it, Userpilot won't be able to recognize your users, and mobile content won't be displayed to them.
</Warning>

**Recommended Usage:**

* **On user authentication (login):** Immediately call `identify` when a user signs in to establish their identity for all future events.
* **On app launch for authenticated users:** If the user has a valid authenticated session, call `identify` at app launch.
* **Upon property updates:** Whenever user or company properties change.

<CodeGroup>
  ```swift Swift theme={null}
  userpilot.identify(
      userId: "<USER_ID>",
      properties: [
          "name": "John Doe",
          "email": "user@example.com",
          "created_at": "2019-10-17",
          "role": "Admin"
      ],
      company: [
          "id": "<COMPANY_ID>",
          "name": "Acme Labs",
          "created_at": "2019-10-17",
          "plan": "Free"
      ]
  )
  ```

  ```c Obj-c theme={null}
  [userpilot identifyWithUserId:@"<USER_ID>"
                      properties:@{
                          @"name": @"John Doe",
                          @"email": @"user@example.com",
                          @"created_at": @"2019-10-17",
                          @"role": @"Admin"
                      }
                      company:@{
                          @"id": @"<COMPANY_ID>",
                          @"name": @"Acme Labs",
                          @"created_at": @"2019-10-17",
                          @"plan": @"Free"
                      }];
  ```
</CodeGroup>

**Properties Guidelines**

* The `id` key is required in company properties to identify a unique company.
* Userpilot supports String, Numeric, and Date types.
* Send date values in ISO8601 format.
* If you plan to use Userpilot's localization features, pass the user property `locale_code` with a value that adheres to ISO 639-1 format.
* Userpilot's reserved properties have pre-determined types and improve the profiles interface in the dashboard:
  * Use key `email` to pass the user's email.
  * Use key `name` to pass the user's or company's name.
  * Use key `created_at` to pass the user's or company's signup date.

<Tip>
  **Notes**

  * Make sure your User ID source is consistent across all platform installations (Web, Android, and iOS).
  * While properties are optional, they are essential for Userpilot's segmentation capabilities. We encourage you to define properties with the people responsible for Userpilot integration.
</Tip>

## Track Screens (Required)

Tracking screens is crucial for unlocking Userpilot’s core engagement and analytics capabilities. Screen views are used to trigger eligible in-app experiences, improve targeting, and provide context for analytics by associating subsequent events with the currently active screen.

<Tabs>
  <Tab title="Auto Capture">
    Userpilot SDK supports automatic screen tracking for iOS applications, allowing screen views to be captured without manually sending screen events.

    When Auto Capture is enabled, the SDK automatically detects and tracks screens across your app lifecycle.

    ```swift theme={null}
    Userpilot(config: Userpilot.Config(token: "<APP_TOKEN>")
        .enableScreenAutoCapture()
    )
    ```

    <Tip>
      **Note**

      Auto Capture automatically tracks screen views and ignores manually sent `screen` events while enabled.

      If you are migrating from manual screen tracking, please review the migration guide [here](https://docs.userpilot.com/data-events/mobile-screen-tracking/mobile-screen-auto-capture#important).
    </Tip>
  </Tab>

  <Tab title="Manual Tracking">
    If Auto Capture is disabled, you can manually track screens by calling the `screen` API whenever a user navigates to a new screen.

    <CodeGroup>
      ```swift Swift theme={null}
      userpilot.screen("Profile")
      ```

      ```c Obj-c theme={null}
      [userpilot screenWithTitle:@"Profile"];
      ```
    </CodeGroup>
  </Tab>
</Tabs>

## Track Events

Log any meaningful action the user performs. Events can be button clicks, form submissions, or any custom activity you want to analyze. Optionally, you can pass metadata with the event to provide specific context.

<CodeGroup>
  ```swift Swift theme={null}
  userpilot.track("Added to Cart", properties: ["itemId": "sku_456", "price": 29.99])
  ```

  ```c Obj-c theme={null}
  [userpilot trackWithEventName:@"Added to Cart"
                     properties:@{
                         @"itemId": @"sku_456",
                         @"price": @29.99
                     }];
  ```
</CodeGroup>

## Logout

When a user logs out, call `logout` to clear the current user context. This ensures subsequent events are no longer associated with the previous user.

<CodeGroup>
  ```swift Swift theme={null}
  userpilot.logout()
  ```

  ```c Obj-c theme={null}
  [userpilot logout];
  ```
</CodeGroup>

## Anonymous Users

If a user is not authenticated, call `anonymous` to track events without a user ID. This is useful for pre-signup flows or guest user sessions.

<CodeGroup>
  ```swift Swift theme={null}
  userpilot.anonymous()
  ```

  ```c Obj-c theme={null}
  [userpilot anonymous];
  ```
</CodeGroup>

<Warning>
  Anonymous users are counted towards your Monthly Active Users usage. You should take your account's MAU limit into consideration before applying this API.
</Warning>

## Experiences

Trigger a specific experience programmatically using its ID. This API allows you to manually initiate an experience within your application.

<CodeGroup>
  ```swift Swift theme={null}
  userpilot.triggerExperience("<EXPERIENCE_ID>")
  ```

  ```c Obj-c theme={null}
  [userpilot triggerExperienceWithId:@"<EXPERIENCE_ID>"];
  ```
</CodeGroup>

End the current active experience:

<CodeGroup>
  ```swift Swift theme={null}
  userpilot.endExperience()
  ```

  ```c Obj-c theme={null}
  [userpilot endExperience];
  ```
</CodeGroup>

## Configuration (Optional)

| **Parameter**                             | **Type**                    | **Description**                                                                                                        |
| ----------------------------------------- | --------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| logging                                   | Bool                        | Enable or disable logs for the SDK.<br /><br />**Default: false**                                                      |
| enableScreenAutoCapture                   | Bool                        | Enables automatic screen tracking.<br /><br />**Default: false**                                                       |
| enableInteractionAutoCapture              | Bool                        | Enables automatic interaction capture.<br /><br />**Default: false**                                                   |
| disableRequestPushNotificationsPermission | Bool                        | Disable push notifications permission request by the SDK.<br /><br />**Default: false**                                |
| useInAppBrowser                           | Boolean                     | Determines whether to open URLs inside SFSafariViewController or use the system browser.<br /><br />**Default: false** |
| navigationHandler                         | UserpilotNavigationDelegate | Handle deep link navigation from experiences and push notifications.                                                   |
| analyticsDelegate                         | UserpilotAnalyticsDelegate  | Broadcasts analytics events to external listeners for tracking and reporting.                                          |
| experienceDelegate                        | UserpilotExperienceDelegate | Notifies about experience display and lifecycle events.                                                                |

**Example Usage**

<CodeGroup>
  ```swift Swift theme={null}
  let userpilot = Userpilot(
      config: Userpilot.Config(token: "<APP_TOKEN>")
          .logging(enabled: true)
          .enableScreenAutoCapture(true)
          .enableInteractionAutoCapture(true)
          .enableUseInAppBrowser(enabled: true)
          .disableRequestPushNotificationsPermission()
  )
  userpilot.navigationDelegate = self
  userpilot.analyticsDelegate = self
  userpilot.experienceDelegate = self
  ```

  ```c Obj-c theme={null}
  Config *config = [[Config alloc] initWithToken:@"<APP_TOKEN>"];
  [config loggingWithEnabled:YES];
  [config enableScreenAutoCaptureWithEnabled:YES];
  [config enableInteractionAutoCaptureWithEnabled:YES];
  [config enableUseInAppBrowserWithEnabled:YES];
  [config disableRequestPushNotificationsPermission];

  Userpilot *userpilot = [[Userpilot alloc] initWithConfig:config];
  userpilot.navigationDelegate = self;
  userpilot.analyticsDelegate = self;
  userpilot.experienceDelegate = self;
  ```
</CodeGroup>

## Sample App

The `Sample` directory in the [GitHub repository](https://github.com/Userpilot/ios-sdk) contains a full example Swift app providing references for usage of the Userpilot API.

<Frame>
  [**For any questions or concerns please reach out to support@userpilot.com**](mailto:support@userpilot.com)
</Frame>
