Install Userpilot on Your iOS App

Introduction

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

This document provides a step-by-step walkthrough of the installation and initialization process, as well as instructions on using the SDK’s public methods.

For more details, examples, or sample implementations, please refer to our GitHub repository.


Prerequisites

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

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

Installation

CocoaPods

  1. Add the Userpilot dependency to your Podfile . Replace <SDK_VERSION> with the latest version available. You can fetch the latest version from here.
target 'YourTargetName' do
  pod 'Userpilot', '~><SDK_VERSION>'
end
  1. 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.


Initialization

To use Userpilot, initialize it once in your App Delegate or Scene Delegate during app launch. This ensures the SDK is ready as soon as your app starts. Replace <APP_TOKEN> with your Application Token, which can be fetched from your Environments Page.

Example

import Userpilot

@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>"))
    }
}

Using the SDK

Once initialized, the SDK provides straightforward methods for identifying users, tracking events, and screen views.

Identifying Users (Required)

This method is required to identify unique users and companies (groups of users) and set their properties. Once identified, all subsequent tracked events and screens will be attributed to that user.

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.

Method:

userpilot?.identify(
    userId: "<USER_ID>",
    userProperties: [
        "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"
    ]
)

Properties Guidelines:

  • Key id 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 are planning to use Userpilot’s localization features, make sure you are passing user property locale_code with a value that adheres to ISO 639-1 format.
  • Use reserved property keys:
    • email for the user’s email.
    • name for the user’s or company’s name.
    • created_at for the user’s or company’s signup date.

Notes

  • Ensure the User ID source is consistent across Web, Android, and iOS.
  • While properties are optional, setting them enhances Userpilot’s segmentation capabilities.

Tracking Screens (Required)

Calling screen is crucial for unlocking Userpilot’s core engagement and analytics capabilities. When a user navigates to a particular screen, invoking screen records that view and triggers any eligible in-app experiences. Subsequent events are also attributed to the most recently tracked screen, providing context for richer analytical insights. For these reasons, we strongly recommend tracking all of your app’s screen views.

userpilot.screen("Profile")

Tracking Events

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

userpilot.track("Added to Cart", properties: ["itemId": "sku_456", "price": 29.99])

Logging Out

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.

userpilot.logout()

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 sessions.

userpilot.anonymous()

Anonymous users count towards your Monthly Active Users usage. Consider your MAU limits before using this method.


Experience


Trigger Experience

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

userpilot.triggerExperience(EXPERIENCE_ID)

End Experience

To manually end the active experience.

userpilot.endExperience()

Configurations (Optional)

If you have additional configuration needs, you can pass a custom configuration when initializing Userpilot. You can enable logging, provide navigation and experience delegates, and set up analytics listeners.

userpilot = Userpilot(
    config: Userpilot.Config(token: "APP_TOKEN")
        .logging(true) // Enable or disable logging
)
userpilot.navigationDelegate = self
userpilot.analyticsDelegate = self
userpilot.experienceDelegate = self

Navigation Handler

Defines how your app handles deep link routes triggered by Userpilot experiences. Implement this to route users to the appropriate screens or external URLs.

Protocol

@objc
public protocol UserpilotNavigationDelegate: AnyObject {
    func navigate(to url: URL, completion: @escaping (Bool) -> Void)
}

The Userpilot SDK automatically handles navigation if you haven't implemented the UserpilotNavigationHandler . When a deep link is external, the SDK will handle it appropriately. For complete control over link handling, you can override the UserpilotNavigationHandler protocol. This allows you to customize the behavior for all types of links as per your requirements.


Analytics Listener

Receives callbacks whenever the SDK tracks an event, screen, or identifies a user. Implement this if you need to integrate with another analytics tool or log events for debugging.

Protocol

@objc
public enum UserpilotAnalytic: Int {
    case identify = 0
    case screen = 1
    case event = 2

    public var rawValueString: String {
        switch self {
        case .identify:
            return "identify"
        case .screen:
            return "screen"
        case .event:
            return "event"
        }
    }
}

@objc
public protocol UserpilotAnalyticsDelegate: AnyObject {
   func didTrack(analytic: UserpilotAnalytic, value: String, properties: [String:     Any]?)
}

Experience Listener

Receives callbacks when Userpilot experiences start, complete, or are dismissed, as well as changes in their step-by-step progression. Implement this if you want to pipe these data points to a destination or react to user actions.

Protocol

@objc
public enum UserpilotExperienceState: Int {
    case started
    case completed
    case dismissed
}

@objc
public protocol UserpilotExperienceDelegate: AnyObject {
    func onExperienceStateChanged(state: UserpilotExperienceState, id: Int, experienceToken: String)
    func onExperienceStepStateChanged(id: Int, experienceToken: String, step: Int, totalSteps: Int)
}

Push Notifications

UserPilot SDK supports handling push notifications to help you deliver targeted messages and enhance user engagement.


Prerequisites

It is recommended to configure your iOS push settings in the Userpilot Settings Studio before setting up push notifications in your app.

To obtain the required keys and configuration details, please refer to the iOS Push Notification Guide.


Enabling Push Notification Capabilities

In Xcode, navigate to the Signing & Capabilities section of your main app target and add the Push Notifications capability.


Configuring Push Notifications

The Userpilot iOS SDK supports receiving push notification so you can reach your users whenever the moment is right.

There are two options for configuring push notification: automatic or manual.

Automatic configuration is the quickest and simplest way to configure push notifications and is recommended for most customers.


Automatic App Configuration

Automatic configuration takes advantage of swizzling to automatically provide the necessary implementations of the required UIApplicationDelegate and UNUserNotificationCenterDelegate methods.

To enable automatic configuration, call Userpilot.enableAutomaticPushConfig() from UIApplicationDelegate.application(_:didFinishLaunchingWithOptions:) .

func application(
_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
   // Automatically configure for push notifications
   Userpilot.enableAutomaticPushConfig()

   // Override point for customization after application launch.
}

Automatic configuration seamlessly integrates with your app's existing push notification handling. It processes only Userpilot notifications, while ensuring that all other notifications continue to be handled by your app’s original logic.



Manually Configuring Push Notifications

Step 1. Register for push notifications

// AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
   application.registerForRemoteNotifications()

// ...
}

Step 2. Set push token for Userpilot

Call Userpilot.setPushToken(_:) from UIApplicationDelegate.application(_:didRegisterForRemoteNotificationsWithDeviceToken:) to pass the APNs token from calling registerForRemoteNotifications() to Userpilot.

// AppDelegate.swift

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
   userpilotInstance.setPushToken(deviceToken)
}

Step 3. Enable push response handling

Update your AppDelegate to conform to the UNUserNotificationCenterDelegate protocol and assign self the delegate in application(_:didFinishLaunchingWithOptions:) .


Implement userNotificationCenter(_:didReceive:withCompletionHandler:) and pass the received notification response to Userpilot.didReceiveNotification(response:completionHandler:) .

// AppDelegate.swift

@main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
   func application(_ application: UIApplication, didFinishLaunchingWithOptions  launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
      application.registerForRemoteNotifications()
   UNUserNotificationCenter.current().delegate = self

   }

   func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive   response: UNNotificationResponse, withCompletionHandler completionHandler:   @escaping () -> Void) {
      if userpilotInstance.didReceiveNotification(response: response, completionHandler: completionHandler) {
  // NOTE: Userpilot calls the completion handler if the notification is an   Userpilot notification.
          return
      }
      completionHandler()
   }
}

Step 4. Configure foreground handling

Configure handling of push notifications received while your app is in the foreground by implementing userNotificationCenter(_:willPresent:withCompletionHandler:) .

// AppDelegate.swift

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
   completionHandler([.banner, .list])
}

For more details refer to AppDelegate+PushNotification.swift


Sample

The Sample directory in GitHub repository contains a full example swift app providing references for usage of the Userpilot API.

Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.