### Complete Quickstart Code Example Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/index.html A runnable example combining initialization and event tracking. This demonstrates the core workflow for getting started with Mixpanel in an iOS application. ```swift import Mixpanel func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { ... // Other setup code Mixpanel.initialize(token: "MIXPANEL_TOKEN", trackAutomaticEvents: false) Mixpanel.mainInstance().track(event: "Sign Up", properties: [ "source": "Pat's affiliate site", "Opted out of email": true ]) ... // Other setup code return true } ``` -------------------------------- ### Complete Quickstart Code Example Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/index.html A runnable example combining initialization and event tracking. This snippet demonstrates the essential steps for getting started with Mixpanel in your Swift application. ```swift import Mixpanel func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { ... // Other setup code Mixpanel.initialize(token: "MIXPANEL_TOKEN", trackAutomaticEvents: false) Mixpanel.mainInstance().track(event: "Sign Up", properties: [ "source": "Pat's affiliate site", "Opted out of email": true ]) ... // Other setup code } ``` -------------------------------- ### Initialize and Track Event - Swift Source: https://github.com/mixpanel/mixpanel-swift/blob/master/README.md A complete example demonstrating initialization of the Mixpanel SDK and tracking an event with properties. This is suitable for application setup. ```swift import Mixpanel func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { ... Mixpanel.initialize(token: "MIXPANEL_TOKEN", trackAutomaticEvents: false) Mixpanel.mainInstance().track(event: "Sign Up", properties: [ "source": "Pat's affiliate site", "Opted out of email": true ]) ... } ``` -------------------------------- ### Start Event Timer Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/MixpanelInstance.html Starts a timer for an event. When the event is later tracked, its duration will be automatically recorded as a property. This is useful for measuring event durations. ```swift public func time(event: String) ``` -------------------------------- ### Start Event Timer Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Classes/MixpanelInstance.html Starts a timer for a specific event. When the event is later tracked using `track()`, the duration since this method was called will be automatically added as a property. Useful for measuring event durations. ```APIDOC ## Start Event Timer ### Description Starts a timer for a specific event. When the event is later tracked using `track()`, the duration since this method was called will be automatically added as a property. Useful for measuring event durations. ### Method Signature ```swift public func time(event: String) ``` ### Parameters - `event` (String): The name of the event to be timed. ``` -------------------------------- ### Accessing Mixpanel Instance Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Provides methods to access the initialized Mixpanel instance. `Mixpanel.mainInstance()` retrieves the default instance, while `Mixpanel.getInstance(name:)` allows access to named instances. `Mixpanel.safeMainInstance()` offers a nil-safe way to get the main instance. ```APIDOC ## Accessing the Instance `Mixpanel.mainInstance()` returns the default initialized instance. `Mixpanel.getInstance(name:)` retrieves a named instance. `Mixpanel.safeMainInstance()` returns nil instead of asserting if uninitialized. ```swift import Mixpanel // Access the main (last initialized) instance let mp = Mixpanel.mainInstance() // Access a named instance (useful when tracking to multiple projects) Mixpanel.initialize(token: "TOKEN_A", trackAutomaticEvents: false, instanceName: "projectA") Mixpanel.initialize(token: "TOKEN_B", trackAutomaticEvents: false, instanceName: "projectB") let projectA = Mixpanel.getInstance(name: "projectA") let projectB = Mixpanel.getInstance(name: "projectB") projectA?.track(event: "Purchase", properties: ["item": "Pro Plan"]) projectB?.track(event: "Purchase", properties: ["item": "Pro Plan"]) // Safely get main instance without crashing (returns nil if not initialized) if let mp = Mixpanel.safeMainInstance() { mp.track(event: "Safe Track") } ``` ``` -------------------------------- ### Get Super Properties Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/MixpanelInstance.html Returns the currently set super properties. ```APIDOC ## Get Super Properties ### Description Returns the currently set super properties. ### Method Signature ```swift public func currentSuperProperties() -> [String : Any] ``` ### Return Value * `[String : Any]`: A dictionary containing the current super properties. ``` -------------------------------- ### Get Mixpanel Instance by Name Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Classes/Mixpanel.html Retrieves a previously initialized Mixpanel instance using its unique name. This is useful when managing multiple instances within the same application. ```swift open class func getInstance(name: String) -> MixpanelInstance? ``` -------------------------------- ### Get Main Mixpanel Instance Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Classes/Mixpanel.html Returns the primary Mixpanel instance. If multiple instances are initialized without explicit names, this method returns the last one that was added. ```swift open class func mainInstance() -> MixpanelInstance ``` -------------------------------- ### Timed Event Tracking in Swift Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Starts a timer for an event, automatically appending the elapsed duration as '$duration' when the event is tracked. Use `eventElapsedTime` to check duration without stopping. Ensure Mixpanel is imported and initialized. ```swift import Mixpanel let mp = Mixpanel.mainInstance() // Start timing when the user begins an upload mp.time(event: "Image Upload") // Check elapsed time without stopping the timer let elapsed = mp.eventElapsedTime(event: "Image Upload") print("Elapsed so far: \(elapsed)s") // Track the event — $duration is appended automatically uploadImage { result in mp.track(event: "Image Upload", properties: [ "file_size_kb": 1024, "success": result == .success ]) // SDK automatically adds "$duration": } // Clear a specific timer (e.g., if upload was cancelled) mp.clearTimedEvent(event: "Image Upload") // Clear all active timers mp.clearTimedEvents() ``` -------------------------------- ### init(token:flushInterval:instanceName:trackAutomaticEvents:optOutTrackingByDefault:useUniqueDistinctId:superProperties:serverURL:proxyServerConfig:useGzipCompression:featureFlagsEnabled:featureFlagsContext:deviceIdProvider:featureFlagOptions:) Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/MixpanelOptions.html Initializes MixpanelOptions with various configuration parameters. ```APIDOC ## Initializer: init(token:flushInterval:instanceName:trackAutomaticEvents:optOutTrackingByDefault:useUniqueDistinctId:superProperties:serverURL:proxyServerConfig:useGzipCompression:featureFlagsEnabled:featureFlagsContext:deviceIdProvider:featureFlagOptions:) ### Description Initializes MixpanelOptions with various configuration parameters. ### Declaration ```swift public init( token: String, flushInterval: Double = 60, instanceName: String? = nil, trackAutomaticEvents: Bool = false, optOutTrackingByDefault: Bool = false, useUniqueDistinctId: Bool = false, superProperties: Properties? = nil, serverURL: String? = nil, proxyServerConfig: ProxyServerConfig? = nil, useGzipCompression: Bool = true, // NOTE: This is a new default value! featureFlagsEnabled: Bool = false, featureFlagsContext: [String: Any] = [:], deviceIdProvider: (() -> String?)? = nil, featureFlagOptions: FeatureFlagOptions? = nil ) ``` ``` -------------------------------- ### initialize(token:flushInterval:instanceName:optOutTrackingByDefault:useUniqueDistinctId:superProperties:serverURL:useGzipCompression:trackAutomaticEvents:) Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Classes/Mixpanel.html Initializes an instance of the Mixpanel API with the provided project token (MAC OS ONLY). This method supports custom server URLs and gzip compression. ```APIDOC ## initialize(token:flushInterval:instanceName:optOutTrackingByDefault:useUniqueDistinctId:superProperties:serverURL:useGzipCompression:trackAutomaticEvents:) ### Description Initializes an instance of the API with the given project token (MAC OS ONLY). Returns a new Mixpanel instance API object, allowing for multiple instances to be created. ### Method `open class func initialize( token apiToken: String, flushInterval: Double = 60, instanceName: String? = nil, optOutTrackingByDefault: Bool = false, useUniqueDistinctId: Bool = false, superProperties: Properties? = nil, serverURL: URL? = nil, useGzipCompression: Bool = false, trackAutomaticEvents: Bool ) -> MixpanelInstance ``` -------------------------------- ### mainInstance() Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/Mixpanel.html Retrieves the main Mixpanel instance. ```APIDOC ## mainInstance() ### Description Returns the main Mixpanel instance. ### Declaration ```swift open class func mainInstance() -> MixpanelInstance ``` ### Return Value Returns the main Mixpanel instance. ``` -------------------------------- ### Get Group Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Classes/MixpanelInstance.html Retrieves a group object. This method is currently undocumented in terms of its specific functionality beyond its signature. ```APIDOC ## Get Group ### Description Retrieves a group object. This method is currently undocumented in terms of its specific functionality beyond its signature. ### Method Signature ```swift public func getGroup(groupKey: String, groupID: MixpanelType) -> Group ``` ### Parameters - `groupKey` (String): The key for the group. - `groupID` (MixpanelType): The ID of the group. ``` -------------------------------- ### Initialize Mixpanel SDK with MixpanelOptions Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Initializes the Mixpanel SDK using a `MixpanelOptions` object for advanced configuration, including feature flags, proxy servers, and custom device ID providers. ```APIDOC ## Initialization with MixpanelOptions `MixpanelOptions` is a strongly-typed configuration object for advanced initialization, including feature flags, proxy servers, gzip compression, and a custom device ID provider. ```swift import Mixpanel // Build an options object with all advanced settings let options = MixpanelOptions( token: "YOUR_PROJECT_TOKEN", flushInterval: 45, instanceName: "primary", trackAutomaticEvents: false, optOutTrackingByDefault: false, useUniqueDistinctId: false, superProperties: ["app": "MyApp"], serverURL: "https://api-eu.mixpanel.com", // EU data residency useGzipCompression: true, featureFlagOptions: FeatureFlagOptions( enabled: true, prefetchFlags: true, context: ["platform": "iOS"] ), deviceIdProvider: { // Return a custom device ID (e.g., from Keychain) return MyKeychain.getOrCreateDeviceId() } ) let mixpanel = Mixpanel.initialize(options: options) ``` ``` -------------------------------- ### ServerProxyResource Initializer Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Structs/ServerProxyResource.html Initializes a new ServerProxyResource with optional query items and required headers. ```APIDOC ## ServerProxyResource ### Description Represents a resource for a server proxy, allowing configuration of query items and headers. ### Initializer #### `init(queryItems: [URLQueryItem]?, headers: [String : String])` Initializes a `ServerProxyResource` instance. * **queryItems** (`[URLQueryItem]?`) - Optional array of URL query items. * **headers** (`[String : String]`) - Dictionary of HTTP headers. This parameter is required. ``` -------------------------------- ### Get Event Elapsed Time Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/MixpanelInstance.html Retrieves the time elapsed for a named event since `time(event:)` was called. ```APIDOC ## Get Event Elapsed Time ### Description Retrieves the time elapsed for a named event since `time(event:)` was called. ### Method Signature ```swift public func eventElapsedTime(event: String) -> Double ``` ### Parameters * `event` (String): The name of the event to retrieve the elapsed time for, which must have been previously passed to `time(event:)`. ``` -------------------------------- ### initialize(token:trackAutomaticEvents:flushInterval:instanceName:optOutTrackingByDefault:useUniqueDistinctId:superProperties:serverURL:useGzipCompression:) Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/Mixpanel.html Initializes a new Mixpanel instance with the provided project token and configuration options. This method allows for multiple Mixpanel instances, which is useful for sending data to different projects. It's recommended to provide an `instanceName` for easier management of multiple instances. ```APIDOC ## initialize(token:trackAutomaticEvents:flushInterval:instanceName:optOutTrackingByDefault:useUniqueDistinctId:superProperties:serverURL:useGzipCompression:) ### Description Initializes an instance of the API with the given project token. Returns a new Mixpanel instance API object. This allows you to create more than one instance of the API object, which is convenient if you’d like to send data to more than one Mixpanel project from a single app. If you have more than one Mixpanel instance, it is beneficial to initialize the instances with an instanceName. Then they can be reached by calling getInstance with name. ### Method `class func initialize( token apiToken: String, trackAutomaticEvents: Bool, flushInterval: Double = 60, instanceName: String? = nil, optOutTrackingByDefault: Bool = false, useUniqueDistinctId: Bool = false, superProperties: Properties? = nil, serverURL: String? = nil, useGzipCompression: Bool = false ) -> MixpanelInstance ### Parameters #### Path Parameters - `apiToken` (String) - your project token - `trackAutomaticEvents` (Bool) - Whether or not to collect common mobile events - `flushInterval` (Double) - Optional. Interval to run background flushing - `instanceName` (String?) - Optional. The name you want to uniquely identify the Mixpanel Instance. It is useful when you want more than one Mixpanel instance under the same project token. - `optOutTrackingByDefault` (Bool) - Optional. Whether or not to be opted out from tracking by default - `useUniqueDistinctId` (Bool) - Optional. whether or not to use the unique device identifier as the distinct_id - `superProperties` (Properties?) - Optional. Dictionary of properties to be sent with every event. - `serverURL` (String?) - Optional. Custom server URL for sending data. - `useGzipCompression` (Bool) - Optional. Whether to use gzip compression for data sent to the server. ### Returns - `MixpanelInstance` - A new Mixpanel instance object. ``` -------------------------------- ### Get Group Information Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/MixpanelInstance.html Retrieves group information based on the provided group key and group ID. This method is currently undocumented. ```swift public func getGroup(groupKey: String, groupID: MixpanelType) -> Group ``` -------------------------------- ### ProxyServerConfig Initialization Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Structs/ProxyServerConfig.html Initializes a new ProxyServerConfig instance. This initializer is optional and may return nil if the provided server URL is invalid. ```APIDOC ## `init(serverUrl:delegate:)` Initializes a new `ProxyServerConfig` instance. ### Parameters - `serverUrl` (String) - The URL of the proxy server. - `delegate` (MixpanelProxyServerDelegate?) - An optional delegate object to handle proxy server events. ### Declaration ```swift public init?(serverUrl: String, delegate: MixpanelProxyServerDelegate? = nil) ``` ``` -------------------------------- ### Get Event Elapsed Time Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Classes/MixpanelInstance.html Retrieves the time elapsed for a named event since `time(event:)` was called. Returns the duration in seconds. ```APIDOC ## Get Event Elapsed Time ### Description Retrieves the time elapsed for a named event since `time(event:)` was called. Returns the duration in seconds. ### Method Signature ```swift public func eventElapsedTime(event: String) -> Double ``` ### Parameters - `event` (String): The name of the event for which to retrieve the elapsed time. ``` -------------------------------- ### Async Get All Feature Flags Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Asynchronously retrieve all available feature flag variants at once. This is useful for fetching multiple flags in a single call. ```swift // Get all variants at once mp.flags.getAllVariants { variants in for (flagName, variant) in variants { print("\(flagName): \(variant.key) = \(variant.value ?? "nil")") } } ``` -------------------------------- ### Initialize Mixpanel SDK with MixpanelOptions Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Configure advanced SDK settings like feature flags, proxy servers, and custom device IDs using MixpanelOptions. This provides granular control over SDK behavior. ```swift import Mixpanel // Build an options object with all advanced settings let options = MixpanelOptions( token: "YOUR_PROJECT_TOKEN", flushInterval: 45, instanceName: "primary", trackAutomaticEvents: false, optOutTrackingByDefault: false, useUniqueDistinctId: false, superProperties: ["app": "MyApp"], serverURL: "https://api-eu.mixpanel.com", // EU data residency useGzipCompression: true, featureFlagOptions: FeatureFlagOptions( enabled: true, prefetchFlags: true, context: ["platform": "iOS"] ), deviceIdProvider: { // Return a custom device ID (e.g., from Keychain) return MyKeychain.getOrCreateDeviceId() } ) let mixpanel = Mixpanel.initialize(options: options) ``` -------------------------------- ### Time Event Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/MixpanelInstance.html Starts a timer for an event. The timer will stop and its duration will be added as a property when the corresponding event is tracked. This is useful for measuring event durations. ```APIDOC ## Time Event ### Description Starts a timer for an event. The timer will stop and its duration will be added as a property when the corresponding event is tracked. This is useful for measuring event durations. ### Method Signature ```swift public func time(event: String) ``` ### Parameters * `event` (String): The name of the event to be timed. ``` -------------------------------- ### ServerProxyResource Initializer Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Structs/ServerProxyResource.html Initializes a new ServerProxyResource with specified query items and headers. ```APIDOC ## ServerProxyResource Initialization ### Description Initializes a new `ServerProxyResource` instance. ### Parameters - `queryItems` ([`URLQueryItem?`]) - An optional array of URL query items. - `headers` ([`[String: String]`]) - A dictionary of headers. ``` -------------------------------- ### Get Current Super Properties Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/MixpanelInstance.html Returns a dictionary containing all currently set super properties. These properties are automatically sent with every tracked event. ```swift public func currentSuperProperties() -> [String : Any] ``` -------------------------------- ### initialize(token:trackAutomaticEvents:flushInterval:instanceName:optOutTrackingByDefault:useUniqueDistinctId:superProperties:proxyServerConfig:useGzipCompression:) Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/Mixpanel.html Initializes a new instance of the Mixpanel API with the provided project token and configuration options. This method allows for multiple Mixpanel instances, useful for sending data to different projects. ```APIDOC ## initialize(token:trackAutomaticEvents:flushInterval:instanceName:optOutTrackingByDefault:useUniqueDistinctId:superProperties:proxyServerConfig:useGzipCompression:) ### Description Initializes an instance of the API with the given project token. Returns a new Mixpanel instance API object. This allows you to create more than one instance of the API object, which is convenient if you’d like to send data to more than one Mixpanel project from a single app. Important If you have more than one Mixpanel instance, it is beneficial to initialize the instances with an instanceName. Then they can be reached by calling getInstance with name. ### Declaration Swift @discardableResult open class func initialize( token apiToken: String, trackAutomaticEvents: Bool, flushInterval: Double = 60, instanceName: String? = nil, optOutTrackingByDefault: Bool = false, useUniqueDistinctId: Bool = false, superProperties: Properties? = nil, proxyServerConfig: ProxyServerConfig, useGzipCompression: Bool = false ) -> MixpanelInstance ### Parameters `_token_` your project token `_trackAutomaticEvents_` Whether or not to collect common mobile events `_flushInterval_` Optional. Interval to run background flushing `_instanceName_` Optional. The name you want to uniquely identify the Mixpanel Instance. It is useful when you want more than one Mixpanel instance under the same project token. `_optOutTrackingByDefault_` Optional. Whether or not to be opted out from tracking by default `_useUniqueDistinctId_` Optional. whether or not to use the unique device identifier as the distinct_id `_superProperties_` Optional. Super properties dictionary to register during initialization `_proxyServerConfig_` Optional. Setup for proxy server. `_useGzipCompression_` Optional. Whether to use gzip compression for network requests. ### Return Value returns a mixpanel instance if needed to keep throughout the project. You can always get the instance by calling getInstance(name) ``` -------------------------------- ### ProxyServerConfig Initialization Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Structs/ProxyServerConfig.html Initializes a new ProxyServerConfig instance. This initializer is undocumented but appears to be the primary way to create a configuration object. ```APIDOC ## ProxyServerConfig Initialization ### Description Initializes a new `ProxyServerConfig` instance with a server URL and an optional delegate. ### Method `init(serverUrl:delegate:)` ### Parameters #### Path Parameters - **serverUrl** (String) - Required - The URL of the proxy server. - **delegate** (MixpanelProxyServerDelegate?) - Optional - The delegate object for handling proxy server events. ### Declaration ```swift public init?(serverUrl: String, delegate: MixpanelProxyServerDelegate? = nil) ``` ``` -------------------------------- ### Get Event Elapsed Time Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/MixpanelInstance.html Retrieves the time elapsed for a specific event since the `time(event:)` method was called. Returns the duration in seconds. ```swift public func eventElapsedTime(event: String) -> Double ``` -------------------------------- ### Synchronously Get Feature Flag Variant Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Protocols/MixpanelFlags.html Retrieves the MixpanelFlagVariant for a given flag name synchronously. Returns a fallback variant if the flag is not found or not loaded. ```swift func getVariantSync(_ flagName: String, fallback: MixpanelFlagVariant) -> MixpanelFlagVariant ``` -------------------------------- ### Initialize Mixpanel SDK in AppDelegate Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Set up the Mixpanel SDK singleton in your AppDelegate. Call this before any tracking. Customize flush interval and automatic event tracking. ```swift import Mixpanel // In AppDelegate or SwiftUI App init func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { Mixpanel.initialize( token: "YOUR_PROJECT_TOKEN", trackAutomaticEvents: false, // set true to auto-collect common mobile events flushInterval: 30, // flush every 30 seconds (default: 60) optOutTrackingByDefault: false, // respect GDPR opt-out useUniqueDistinctId: false, // use random UUID (true = use IDFV) superProperties: ["platform": "iOS", "version": "2.0"] ) return true } // SwiftUI App entry point @main struct MyApp: App { init() { Mixpanel.initialize(token: "YOUR_PROJECT_TOKEN", trackAutomaticEvents: false) } var body: some Scene { WindowGroup { ContentView() } } } ``` -------------------------------- ### initialize(token:trackAutomaticEvents:flushInterval:instanceName:optOutTrackingByDefault:useUniqueDistinctId:superProperties:serverURL:useGzipCompression:) Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Classes/Mixpanel.html Initializes an instance of the Mixpanel API with the provided project token and configuration options. This method allows for the creation of multiple Mixpanel instances, each potentially configured with a unique name, for sending data to different Mixpanel projects. ```APIDOC ## initialize(token:trackAutomaticEvents:flushInterval:instanceName:optOutTrackingByDefault:useUniqueDistinctId:superProperties:serverURL:useGzipCompression:) ### Description Initializes an instance of the API with the given project token. Returns a new Mixpanel instance API object. This allows you to create more than one instance of the API object, which is convenient if you’d like to send data to more than one Mixpanel project from a single app. Important If you have more than one Mixpanel instance, it is beneficial to initialize the instances with an instanceName. Then they can be reached by calling getInstance with name. ### Method `class func initialize( token apiToken: String, trackAutomaticEvents: Bool, flushInterval: Double = 60, instanceName: String? = nil, optOutTrackingByDefault: Bool = false, useUniqueDistinctId: Bool = false, superProperties: Properties? = nil, serverURL: String? = nil, useGzipCompression: Bool = false ) -> MixpanelInstance ### Parameters #### Path Parameters - **apiToken** (String) - your project token - **trackAutomaticEvents** (Bool) - Whether or not to collect common mobile events - **flushInterval** (Double) - Optional. Interval to run background flushing - **instanceName** (String?) - Optional. The name you want to uniquely identify the Mixpanel Instance. It is useful when you want more than one Mixpanel instance under the same project token. - **optOutTrackingByDefault** (Bool) - Optional. Whether or not to be opted out from tracking by default - **useUniqueDistinctId** (Bool) - Optional. whether or not to use the unique device identifier as the distinct_id - **superProperties** (Properties?) - Optional. A dictionary of properties to be sent with every event. - **serverURL** (String?) - Optional. The custom server URL to send data to. - **useGzipCompression** (Bool) - Optional. Whether or not to use gzip compression for data sent to the server. ### Response #### Success Response (MixpanelInstance) - **MixpanelInstance** - The initialized Mixpanel instance. ``` -------------------------------- ### Get Current Super Properties Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Classes/MixpanelInstance.html Returns a dictionary containing all currently set super properties. Super properties are automatically included with every event tracked. ```APIDOC ## Get Current Super Properties ### Description Returns a dictionary containing all currently set super properties. Super properties are automatically included with every event tracked. ### Method Signature ```swift public func currentSuperProperties() -> [String : Any] ``` ### Return Value - `[String : Any]`: A dictionary representing the current super properties. ``` -------------------------------- ### Initialize Mixpanel SDK Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Initializes the Mixpanel SDK singleton with a project token and optional automatic event tracking. This method must be called before any tracking operations. ```APIDOC ## Initialize Mixpanel SDK `Mixpanel.initialize(token:trackAutomaticEvents:)` sets up the SDK singleton. Must be called before any tracking. Returns a `MixpanelInstance` and also registers as the main instance accessible via `Mixpanel.mainInstance()`. ```swift import Mixpanel // In AppDelegate or SwiftUI App init func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { Mixpanel.initialize( token: "YOUR_PROJECT_TOKEN", trackAutomaticEvents: false, // set true to auto-collect common mobile events flushInterval: 30, // flush every 30 seconds (default: 60) optOutTrackingByDefault: false, // respect GDPR opt-out useUniqueDistinctId: false, // use random UUID (true = use IDFV) superProperties: ["platform": "iOS", "version": "2.0"] ) return true } // SwiftUI App entry point @main struct MyApp: App { init() { Mixpanel.initialize(token: "YOUR_PROJECT_TOKEN", trackAutomaticEvents: false) } var body: some Scene { WindowGroup { ContentView() } } } ``` ``` -------------------------------- ### Async Get Feature Flag Variant Value Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Asynchronously retrieve only the value of a feature flag variant. Use this when you only need the specific value and not the full variant object. ```swift // Async get just the variant value mp.flags.getVariantValue("discount_percentage", fallbackValue: 0) { value in if let discount = value as? Int { applyDiscount(discount) } } ``` -------------------------------- ### Initialize Mixpanel with Project Token Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/Mixpanel.html Initializes a new Mixpanel instance API object with the provided project token. This allows for multiple instances, useful for sending data to different Mixpanel projects. Consider using instanceName for clarity if multiple instances are created. ```swift @discardableResult open class func initialize( token apiToken: String, trackAutomaticEvents: Bool, flushInterval: Double = 60, instanceName: String? = nil, optOutTrackingByDefault: Bool = false, useUniqueDistinctId: Bool = false, superProperties: Properties? = nil, serverURL: String? = nil, useGzipCompression: Bool = false ) -> MixpanelInstance ``` -------------------------------- ### getOptions() Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Protocols/MixpanelFlagDelegate.html Retrieves the Mixpanel options. ```APIDOC ## getOptions() ### Description Retrieves the Mixpanel options. ### Declaration Swift ```swift func getOptions() -> MixpanelOptions ``` ``` -------------------------------- ### Initialize Mixpanel with Feature Flags Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Initialize the Mixpanel SDK with feature flag options enabled, including prefetching flags and setting custom targeting context. ```swift import Mixpanel let mp = Mixpanel.initialize(options: MixpanelOptions( token: "YOUR_TOKEN", featureFlagOptions: FeatureFlagOptions( enabled: true, prefetchFlags: true, // fetch on init context: ["platform": "iOS"] // custom targeting context ) )) ``` -------------------------------- ### Async Get Feature Flag Variant Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Asynchronously retrieve the full variant object for a feature flag, including its key and value. Provides a fallback variant if the flag is not found. ```swift // Async get a variant with full metadata mp.flags.getVariant("onboarding_variant", fallback: MixpanelFlagVariant(key: "control")) { variant in print("Variant key: \(variant.key)") // e.g., "treatment_a" print("Variant value: \(variant.value ?? "nil")") } ``` -------------------------------- ### MixpanelOptions Initializer Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Classes/MixpanelOptions.html Initializes MixpanelOptions with various configuration parameters. ```APIDOC ## MixpanelOptions Initializer ### Description Initializes MixpanelOptions with various configuration parameters. ### Declaration Swift ```swift public init( token: String, flushInterval: Double = 60, instanceName: String? = nil, trackAutomaticEvents: Bool = false, optOutTrackingByDefault: Bool = false, useUniqueDistinctId: Bool = false, superProperties: Properties? = nil, serverURL: String? = nil, proxyServerConfig: ProxyServerConfig? = nil, useGzipCompression: Bool = true, // NOTE: This is a new default value! featureFlagsEnabled: Bool = false, featureFlagsContext: [String: Any] = [:], deviceIdProvider: (() -> String?)? = nil, featureFlagOptions: FeatureFlagOptions? = nil ) ``` ``` -------------------------------- ### Asynchronously Get Feature Flag Variant Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Protocols/MixpanelFlags.html Asynchronously retrieves the MixpanelFlagVariant for a given flag name. A completion handler is called with the variant or a fallback. This method also triggers necessary tracking logic. ```swift func getVariant( _ flagName: String, fallback: MixpanelFlagVariant, completion: @escaping (MixpanelFlagVariant) -> Void) ``` -------------------------------- ### Configure Mixpanel Swift SDK with Proxy Server and Custom Delegate Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Initialize the Mixpanel SDK with a proxy server and a custom delegate to provide per-request headers and query parameters. The delegate's `mixpanelResourceForProxyServer` method should return a `ServerProxyResource` object. ```swift import Mixpanel // Proxy with custom headers and query params per request class MyProxyDelegate: MixpanelProxyServerDelegate { func mixpanelResourceForProxyServer(_ name: String) -> ServerProxyResource? { return ServerProxyResource( headers: [ "X-Auth-Token": "my-secret", "X-Instance": name ], queryItems: [ URLQueryItem(name: "env", value: "production") ] ) } } let delegate = MyProxyDelegate() if let proxyConfig = ProxyServerConfig( serverUrl: "https://proxy.mycompany.com", delegate: delegate ) { Mixpanel.initialize( token: "YOUR_TOKEN", trackAutomaticEvents: false, proxyServerConfig: proxyConfig ) } ``` -------------------------------- ### Asynchronously Get All Feature Flag Variants Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Protocols/MixpanelFlags.html Asynchronously retrieves all feature flag variants. If flags are not ready, an attempt will be made to load them. The completion handler is typically invoked on the main thread. Does not trigger tracking. ```swift func getAllVariants(completion: @escaping ([String : MixpanelFlagVariant]) -> Void) ``` -------------------------------- ### Initialize Mixpanel Instance Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Classes/Mixpanel.html Initializes a Mixpanel instance with a project token and various configuration options. Use this for iOS and Android. It allows for custom super properties, proxy server configuration, and gzip compression. ```swift @discardableResult open class func initialize( token apiToken: String, trackAutomaticEvents: Bool, flushInterval: Double = 60, instanceName: String? = nil, optOutTrackingByDefault: Bool = false, useUniqueDistinctId: Bool = false, superProperties: Properties? = nil, proxyServerConfig: ProxyServerConfig, useGzipCompression: Bool = false ) -> MixpanelInstance ``` -------------------------------- ### Asynchronously Get Feature Flag Value Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Protocols/MixpanelFlags.html Asynchronously retrieves the underlying value of a feature flag. A completion handler is called with the flag's value or a fallback value. Attempts to load flags if not ready. ```swift func getVariantValue( _ flagName: String, fallbackValue: Any?, completion: @escaping (Any?) -> Void) ``` -------------------------------- ### Initialize Mixpanel with Options Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/Mixpanel.html Initializes an instance of the Mixpanel API using MixpanelOptions. This method is useful for configuring various aspects of the SDK during initialization. ```swift open class func initialize(options: MixpanelOptions) -> MixpanelInstance ``` -------------------------------- ### Initialize Mixpanel with Default Feature Flag Options Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Structs/FeatureFlagOptions.html Use this to enable feature flags with their default prefetching behavior during Mixpanel initialization. ```swift let options = MixpanelOptions( token: "YOUR_TOKEN", featureFlagOptions: FeatureFlagOptions(enabled: true) ) ``` -------------------------------- ### Initialize with Default Opt-Out Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Initialize the Mixpanel SDK with tracking disabled by default. This is useful for GDPR-first applications where users must explicitly consent to tracking. ```swift // Initialize with opt-out as the default state (for GDPR-first apps) Mixpanel.initialize( token: "YOUR_TOKEN", trackAutomaticEvents: false, optOutTrackingByDefault: true // all users start opted out ) // Later, after consent is given: Mixpanel.mainInstance().optInTracking(distinctId: "user_12345") ``` -------------------------------- ### Synchronously Get Feature Flag Value Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Protocols/MixpanelFlags.html Synchronously retrieves the underlying value of a feature flag. This method may block the calling thread and is not recommended for the main UI thread. Returns a fallback value if the flag is not found or not ready. ```swift func getVariantValueSync(_ flagName: String, fallbackValue: Any?) -> Any? ``` -------------------------------- ### mixpanelWillFlush(_:) Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Protocols/MixpanelDelegate.html Asks the delegate if data should be uploaded to the server. Returning true allows the upload, while false defers it. ```APIDOC ## mixpanelWillFlush(_:) ### Description Asks the delegate if data should be uploaded to the server. ### Method func ### Parameters #### Path Parameters - **mixpanel** (MixpanelInstance) - Required - The mixpanel instance ### Return Value - **Bool** - return true to upload now or false to defer until later ``` -------------------------------- ### Get Feature Flag Variant Synchronously Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Protocols/MixpanelFlags.html Synchronously retrieves the complete `MixpanelFlagVariant` for a given flag name. If flags are not ready, it returns the provided fallback variant. This method may block the calling thread and is not recommended for the main UI thread. ```swift func getVariantSync(_: String, fallback: MixpanelFlagVariant) -> MixpanelFlagVariant ``` -------------------------------- ### Configure Mixpanel Swift SDK with a Simple Proxy Server Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Route all Mixpanel network traffic through a specified proxy server during SDK initialization. Ensure the proxy server URL is valid. ```swift import Mixpanel // Simple proxy (all traffic routed through your server) if let proxyConfig = ProxyServerConfig(serverUrl: "https://proxy.mycompany.com") { Mixpanel.initialize( token: "YOUR_TOKEN", trackAutomaticEvents: false, proxyServerConfig: proxyConfig ) } ``` -------------------------------- ### Synchronously Get All Feature Flag Variants Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Protocols/MixpanelFlags.html Synchronously retrieves all fetched feature flag variants. This method may block the calling thread and is not recommended for the main UI thread. Returns an empty dictionary if flags are not loaded or ready. Does not trigger tracking. ```swift func getAllVariantsSync() -> [String : MixpanelFlagVariant] ``` -------------------------------- ### getOptions() Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/MixpanelInstance.html Undocumented ```APIDOC ## getOptions() ### Description Undocumented ### Declaration ```swift public func getOptions() -> MixpanelOptions ``` ``` -------------------------------- ### getOptions() Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Protocols/MixpanelFlagDelegate.html Retrieves the Mixpanel options associated with feature flags. ```APIDOC ## getOptions() ### Description Retrieves the Mixpanel options associated with feature flags. ### Declaration Swift ```swift func getOptions() -> MixpanelOptions ``` ``` -------------------------------- ### safeMainInstance() Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/Mixpanel.html Safely retrieves the main Mixpanel instance if it has been initialized. ```APIDOC ## safeMainInstance() ### Description Returns the main Mixpanel instance if it has been initialized. ### Declaration ```swift public class func safeMainInstance() -> MixpanelInstance? ``` ### Return Value An optional MixpanelInstance, or nil if not yet initialized. ``` -------------------------------- ### Enable Debugging and Logging - Swift Source: https://github.com/mixpanel/mixpanel-swift/blob/master/README.md Enable detailed logging from the Mixpanel library to help with debugging. Set this property to true to see verbose output. ```swift Mixpanel.mainInstance().loggingEnabled = true ``` -------------------------------- ### Initialize FeatureFlagOptions with Custom Context Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Structs/FeatureFlagOptions.html Initialize FeatureFlagOptions with custom context data that will be sent with feature flag fetch requests. ```swift public init( enabled: Bool = false, context: [String: Any] = [:], prefetchFlags: Bool = true ) ``` -------------------------------- ### Add Mixpanel-swift Dependency to Cartfile Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/index.html Use this to include the Mixpanel Swift library as a dependency in your project when using Carthage. ```shell github "mixpanel/mixpanel-swift" ``` -------------------------------- ### mainInstance() Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/Mixpanel.html Returns the primary Mixpanel instance. If multiple instances exist, this method returns the last one that was initialized. ```APIDOC ## mainInstance() ### Description Returns the main instance that was initialized. If not specified explicitly, the main instance is always the last instance added ### Declaration Swift open class func mainInstance() -> MixpanelInstance? ### Return Value returns the main mixpanel instance ``` -------------------------------- ### Initialize Mixpanel Swift SDK Source: https://github.com/mixpanel/mixpanel-swift/blob/master/README.md Import Mixpanel and initialize it within your application's launch method. Set `trackAutomaticEvents` to `false` if you do not want to automatically track events like session start/end. ```swift import Mixpanel func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { ... Mixpanel.initialize(token: "MIXPANEL_TOKEN", trackAutomaticEvents: false) ... } ``` -------------------------------- ### setOnce(properties:) Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/docsets/Mixpanel.docset/Contents/Resources/Documents/Classes/Group.html Sets properties on a Mixpanel group, but only if the property does not already exist. Useful for first-time event tracking. ```APIDOC ## setOnce(properties:) ### Description Sets properties on the current Mixpanel Group, but doesn’t overwrite if there is an existing value. This method is identical to `set:` except it will only set properties that are not already set. It is particularly useful for collecting data about dates representing the first time something happened. ### Parameters - `properties` (Properties) - properties dictionary ``` -------------------------------- ### Access Mixpanel SDK Instances Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Retrieve the default or named Mixpanel instances for tracking events. Use safe access to avoid crashes if the SDK is not initialized. ```swift import Mixpanel // Access the main (last initialized) instance let mp = Mixpanel.mainInstance() // Access a named instance (useful when tracking to multiple projects) Mixpanel.initialize(token: "TOKEN_A", trackAutomaticEvents: false, instanceName: "projectA") Mixpanel.initialize(token: "TOKEN_B", trackAutomaticEvents: false, instanceName: "projectB") let projectA = Mixpanel.getInstance(name: "projectA") let projectB = Mixpanel.getInstance(name: "projectB") projectA?.track(event: "Purchase", properties: ["item": "Pro Plan"]) projectB?.track(event: "Purchase", properties: ["item": "Pro Plan"]) // Safely get main instance without crashing (returns nil if not initialized) if let mp = Mixpanel.safeMainInstance() { mp.track(event: "Safe Track") } ``` -------------------------------- ### MixpanelDelegate mixpanelWillFlush(_:) Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Protocols/MixpanelDelegate.html Asks the delegate if data should be uploaded to the server. Return true to upload now or false to defer until later. ```swift func mixpanelWillFlush(_ mixpanel: MixpanelInstance) -> Bool ``` -------------------------------- ### setOnce(properties:) Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/People.html Set properties on the current user in Mixpanel People, but only if they do not already exist. Useful for initial user data. ```APIDOC ## setOnce(properties:) ### Description Set properties on the current user in Mixpanel People, but doesn’t overwrite if there is an existing value. This method is identical to `set:` except it will only set properties that are not already set. It is particularly useful for collecting data about the user’s initial experience and source, as well as dates representing the first time something happened. ### Method open func setOnce(properties: Properties) ### Parameters #### Request Body - **properties** (Properties) - Dictionary of properties to set. ``` -------------------------------- ### Opt In Tracking with Mixpanel Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/MixpanelInstance.html Call this method to internally track an opt-in event to your project. You can optionally provide a distinct ID and additional properties. ```swift public func optInTracking(distinctId: String? = nil, properties: Properties? = nil) ``` -------------------------------- ### Flush Source: https://context7.com/mixpanel/mixpanel-swift/llms.txt Manually upload the local event queue to Mixpanel servers using `flush()`. Useful before app termination, on logout, or when immediate delivery is required. ```APIDOC ## Flush `flush(performFullFlush:completion:)` manually uploads the local event queue to Mixpanel servers. Useful before app termination, on logout, or when immediate delivery is required. ```swift import Mixpanel let mp = Mixpanel.mainInstance() // Partial flush (default) — sends up to flushBatchSize events mp.flush() // Full flush — sends ALL queued events (use before logout or app termination) mp.flush(performFullFlush: true) { print("All queued events have been sent") } // Adjust flush behavior mp.flushInterval = 30 // flush every 30 seconds (0 = manual only) mp.flushOnBackground = true // flush when app backgrounds (default) mp.flushBatchSize = 25 // events per network request (max 50) // Control upload via delegate class AnalyticsManager: MixpanelDelegate { func mixpanelWillFlush(_ mixpanel: MixpanelInstance) -> Bool { // Return false to delay flushing (e.g., on metered connections) return NetworkMonitor.shared.isOnWiFi } } let manager = AnalyticsManager() mp.delegate = manager ``` ``` -------------------------------- ### mixpanelResourceForProxyServer(_:) Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Protocols/MixpanelProxyServerDelegate.html Asks the delegate to return API resource items like query parameters and headers for the proxy server. This method is called to customize the network requests made by the proxy server. ```APIDOC ## mixpanelResourceForProxyServer(_:) ### Description Asks the delegate to return API resource items like query params & headers for proxy Server. ### Method func ### Parameters #### Path Parameters * **name** (String) - The mixpanel instance #### Return Value ServerProxyResource? - return ServerProxyResource to give custom headers and query params. ``` -------------------------------- ### optInTracking Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/MixpanelInstance.html Tracks an opt-in event to your project. This method can optionally take a distinct ID and additional properties. ```APIDOC ## optInTracking ### Description This method will internally track an opt in event to your project. ### Declaration ```swift public func optInTracking(distinctId: String? = nil, properties: Properties? = nil) ``` ### Parameters - `distinctId` (String?) - An optional string to use as the distinct ID for events. - `properties` (Properties?) - An optional properties dictionary that could be passed to add properties to the opt-in event that is sent to Mixpanel. ``` -------------------------------- ### useGzipCompression Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/MixpanelInstance.html Undocumented ```APIDOC ## useGzipCompression ### Description Undocumented ### Declaration ```swift open var useGzipCompression: Bool { get set } ``` ``` -------------------------------- ### Set Multiple Group Memberships in Swift Source: https://github.com/mixpanel/mixpanel-swift/blob/master/docs/Classes/MixpanelInstance.html Assign a user to a list of groups for a specific group key. The group key must be pre-configured. ```swift public func setGroup(groupKey: String, groupIDs: [MixpanelType]) ```