Getting Started
Please refer to our Quickstart Guide. The Full API Reference, Library Source Code, and an Example Application are documented in our GitHub repo.Installing the Library
You can install the Swift library by using CocoaPods, Carthage, or Swift Package Manager.- Swift Package Manager
- CocoaPods
- Carthage
- In Xcode, select File > Add Packages…
- Enter the package URL for this repository and select version v2.8.0 or above.
Mixpanel into AppDelegate.swift and initialize Mixpanel within application:didFinishLaunchingWithOptions: using your project token.
Swift
SDK Configuration Using MixpanelOptions
Configure the Mixpanel SDK usingMixpanelOptions to customize tracking behavior, data residency, privacy settings, and more.
Configuration Reference
| Config Option | Description | Default |
|---|---|---|
token | Your Mixpanel project token (required) | N/A |
serverURL | Custom API endpoint. Required for EU or India data residency. Takes precedence over proxyServerConfig.serverUrl | US (https://api.mixpanel.com) |
flushInterval | Interval in seconds between automatic flush operations. Set to 0 to disable. See Flushing Events | 60 |
trackAutomaticEvents | Auto-track app lifecycle events. Not recommended — see Legacy Automatically Tracked Events | false |
optOutTrackingByDefault | Start with tracking disabled for GDPR compliance. See Opt Out of Tracking | false |
useIPAddressForGeoLocation | Enable IP-based geolocation. See Disable Geolocation | true |
useUniqueDistinctId | Use device IDFV instead of random UUID. See Custom Device ID Generation | false |
instanceName | Unique identifier for multi-instance setups | Project token |
deviceIdProvider | Custom closure for device ID generation (requires v5.2.0+). See Custom Device ID Generation | nil |
superProperties | Properties automatically added to all events. Can also be set at runtime. See Setting Super Properties | nil |
featureFlagOptions | Feature flags configuration (prefetch behavior and custom context). See Feature Flags Initialization | FeatureFlagOptions(enabled: false) |
proxyServerConfig | Proxy configuration with headers and query params | nil |
useGzipCompression | Enable gzip compression for network requests | true |
Best Practice: Configure all settings (especially
serverURL for data residency) during initialization using MixpanelOptions. This ensures all SDK components (events, profiles, feature flags) use the correct configuration from the start, avoiding potential race conditions.MixpanelInstance.
Common Configuration Example
Swift
Sending Events
Use.track(event:properties:) to send an event by providing the event name and any event properties. This will trigger a request to the /track API endpoint to ingest the event into your project.
The /track endpoint will only validate events with timestamps within the last 5 days of the request. Events with timestamps older than 5 days will not be ingested. See below on best practices for historical imports.
Swift
Timing Events
You can track the time it took for an action to occur, such as an image upload or a comment post, using.time(event:). This will mark the “start” of your action, which you can then finish with a track call. The time duration is then recorded in the “Duration” property.
Swift
Flushing Events
To preserve battery life and customer bandwidth, the Mixpanel library doesn’t send the events you record immediately. Instead, it sends batches to the Mixpanel servers every 60 seconds while your application is running, as well as when the application transitions to the background. Call.flush() manually if you want to force a flush at a particular moment.
Example Usage
Swift
Configuring Flush Interval
The default flush interval is 60 seconds. You can customize this using theflushInterval option in MixpanelOptions (see Configuration Reference). Set to 0 to disable automatic flushing entirely (requires manual .flush() calls).
Recommended: Configure During Initialization
Swift
flushInterval.
Swift
Importing Historical Events
The Swift SDK is a tracking SDK designed for real-time tracking in a client-side environment. Calling.track(event:properties:) triggers a request to our /track API endpoint, which will validate for events with a timestamp that is within the last 5 days of the request. Events older than 5 days will not be ingested.
For bulk import of historical events older than 5 days, we will need to use the /import API endpoint which is optimized for scripting and supports ingesting historical data. We recommend the Python SDK (see the .import_data() function) and mixpanel-utils module (see the import_events() function) which both leverages the /import API for event ingestion.
Setting Super Properties
Super properties are global event properties that you define once and apply to all events. You can set super properties during SDK initialization or at runtime.Setting Super Properties During Initialization
You can set initial super properties using thesuperProperties option in MixpanelOptions (see Configuration Reference).
Example Usage
Swift
Setting Super Properties at Runtime
To register super properties at runtime, call.registerSuperProperties(_:).
Use .registerSuperPropertiesOnce(_:) to register super properties without overwriting existing values.
Example Usage
Swift
Swift
Managing User Identity
You can handle the identity of a user using the.identify() and .reset() methods. Learn more about identity management and identifying users.
Identify
Call.identify() when you know the identity of the current user, passing in their user ID as an argument. This is typically at account registration and at log in.
Swift
Call Reset on Logout
Call.reset() to clear data attributed to a user when they logout. This will clear the local storage and allows you to handle multiple users on a single device.
Example Usage
Swift
Since v2.7.7, Mixpanel stopped using the IFA (ID for Advertisers) as a distinct_id. Calls to
.reset() will generate a new random UUID unless you’ve configured custom device ID behavior. See Custom Device ID Generation for details on using IDFV or implementing custom device ID logic.Custom Device ID Generation
The Swift SDK provides two ways to customize device ID generation (see Configuration Reference):useUniqueDistinctId- Use device IDFV (Identifier for Vendor) instead of random UUIDdeviceIdProvider- Custom closure for implementing your own device ID generation logic
Using Device IDFV
SetuseUniqueDistinctId to true to use the device’s IDFV instead of a random UUID. The IDFV persists across app updates but changes when the app is uninstalled and reinstalled.
Example Usage
Swift
You can also enable IDFV by setting
MIXPANEL_UNIQUE_DISTINCT_ID in build settings Active Compilation Conditions on the Mixpanel framework target. When using IDFV, the ID will not change when you call .reset(), but will change upon app uninstalls/reinstalls.Custom Device ID Provider
The
deviceIdProvider option requires Swift SDK v5.2.0 or later.deviceIdProvider closure to implement custom device ID generation logic. This allows you to control where device IDs are stored and whether they persist across .reset() calls.
If the provider returns nil or an empty string, the SDK will fall back to generating a default device ID (UUID or IDFV based on useUniqueDistinctId).
Example Usage
Swift
.reset() calls. Returning different values generates a new device ID on each reset.
Swift
Storing User Profiles
Once your users are identified, create user profiles by setting profile properties to describe them. Example profile properties include “name”, “email”, “company”, and any other demographic details about the user. The Swift SDK provides a few methods for setting profile properties under thePeople class accessible via .people(). These methods will trigger requests to the /engage API endpoint.
Setting Profile Properties
You must call
.identify() before setting profile properties in order to associate the profile properties you set with the target user. If identify is not called, the profile update will be queued for ingestion until an identify call is made.people.set(property:to:).
If a profile property already exists, it will be overwritten with the latest value provided in the method. If a profile property does not exist, it will be added to the profile.
Example Usage
Swift
Other Types of Profile Updates
There are a few other methods for setting profile properties. See a complete reference of the available methods here A few commonly used people methods are highlighted below:- setOnce()
- append()
- union()
- increment()
The
setOnce(properties:) method set profile properties only if they do not exist yet. If it is setting a profile property that already exists, it will be ignored.Use this method if you want to set profile properties without the risk of overwriting existing data.Example UsageSwift
Group Analytics
Read more about Group Analytics before proceeding. You will need to have the group key defined in your project settings first.
group_key and group_id.
group_keyis the event property that connects event data to a group. (e.g.company)group_idis the identifier for a specific group. (e.g.mixpanel,company_a,company_b, etc.)
Adding Users to a Group
All events must have the group key as an event property in order to be attributed to a group. Without the group key, an event cannot be attributed to a group. Call thesetGroup(groupKey:groupIDs:) to register the current user to a group, which would add the group_key as an event property set to the group_id value to all events moving forward.
Example Usage
Swift
group_key value as a list of multiple group_id values.
Call addGroup(groupKey:groupID:) to add additional group_ids to an existing group key property.
Example Usage
Swift
Adding Group Identifiers to User Profiles
To connect group information to a user profile, include thegroup_key and group_id as a user profile property using the .people.set() call.
Example Usage
Swift
Setting Group Profile Properties
Create a group profiles by setting group properties, similar to a user profile. For example, you may want to describe a company group with properties such as “ARR”, “employee_count”, and “subscription”. To set group profile properties, specify the group that needs to be updated by callinggetGroup(groupKey:groupID:), then set the group properties by chaining the set(properties:) method, which will trigger a request to the /groups API endpoint.
Example Usage
Swift
Other Group Profile Methods
See all of the methods under the MixpanelGroup class here. A few commonly used group methods are highlighted below:- setOnce()
- unset()
- union()
- remove()
The
setOnce(properties:) method set group profile properties only if they do not exist yet. If it is setting a profile property that already exists, it will be ignored.Use this method if you want to set group profile properties without the risk of overwriting existing data.Example UsageSwift
Session Replay
Install the Session Replay SDK for Swift to record replay data. Learn more about Session Replay and implementing Session Replay on iOS.Debugging and Logging
Enable debug mode by setting theloggingEnabled configuration to true.
Example Usage
Swift
Privacy-Friendly Tracking
You have control over the data you send to Mixpanel. The Swift SDK provides methods to help you protect user data. Learn more about Privacy.Opt Out of Tracking
The Swift SDK is initialized with tracking enabled by default. Use theoptOutTracking() method to opt the user out of data tracking and local storage for the current Mixpanel instance.
Example Usage
Swift
Opt Out by Default
For GDPR compliance, you can initialize the SDK with users opted out of tracking by default using theoptOutTrackingByDefault option (see Configuration Reference). Once the user consents to tracking, call optInTracking() to start tracking.
Example Usage
Swift
Data Residency
Setting
serverURL during initialization ensures all requests (events, profiles, and feature flags) use the correct endpoint from the start.EU Data Residency
Route data to Mixpanel’s EU servers by setting theserverURL option to https://api-eu.mixpanel.com during initialization (see Configuration Reference).
Example Usage
Swift
India Data Residency
Route data to Mixpanel’s India servers by setting theserverURL option to https://api-in.mixpanel.com during initialization (see Configuration Reference).
Example Usage
Swift
Disable Geolocation
The Swift SDK parses the request IP address to generate geolocation properties for events and profiles. To disable geolocation and prevent IP-based tracking, setuseIPAddressForGeoLocation to false (see Configuration Reference).
You can configure this during initialization or change it after:
Recommended: Configure During Initialization
Swift
Swift
Legacy Automatically Tracked Events
Mixpanel’s SDKs have a legacy feature to automatically collect common mobile events. We don’t recommend enabling this, as these events rely on client-side state and can be unreliable. ThetrackAutomaticEvents option is set to false by default (see Configuration Reference). You only need to explicitly set this if you want to enable automatic event tracking.
See below table for automatic events tracked by the Swift SDK when trackAutomaticEvents is enabled:
| Raw Name | Display Name | Description |
|---|---|---|
| $ae_first_open | First App Open | Tracks the first time the user has opened the app. This event is retriggered if the user reinstalls the app or clears local storage. A user property First App Open Date ($ae_first_app_open_date) is tracked to indicate the date when app was first opened. |
| $ae_updated | App Updated | Executes when a user updates the app from the previous version. A Version Updated ($ae_updated_version) property is tracked to store the new app version. |
| $ae_session | App Session | Executes when a user spends more than 10 seconds in the app. A Session Length ($ae_session_length) property is tracked to reflect the number of seconds user spent in the session. In addition, there are two user properties tracked: Total App Sessions ($ae_total_app_sessions) and Total App Session Length ($ae_total_app_session_length). |
| $ae_iap | In App Purchase (IAP) | Executes when a user conducts an in-app purchase through your app. Mixpanel provides three properties for this event: Product Name ($ae_iap_name), Product Quantity ($ae_iap_quantity), and Product Price ($ae_iap_price). |