The Unified SDK for Swift is in beta and undergoing testing.
This is the official documentation for the Amplitude Unified SDK for Swift.
The Unified SDK is a wrapper around Amplitude's existing SDKs, providing a simplified interface to use multiple Amplitude products together. It currently includes:
Add the dependency to your Podfile
:
pod 'AmplitudeUnified', '~> 0.0.0'
Run pod install
in the project directory.
Navigate to File
> Swift Package Manager
> Add Package Dependency
. This opens a dialog that allows you to add a package dependency.
Enter the URL https://github.com/amplitude/AmplitudeUnified-Swift
in the search bar.
Xcode automatically resolves to the latest version. Or you can select a specific version.
Click the "Next" button to confirm the addition of the package as a dependency.
Build your project to make sure the package is properly integrated.
You must initialize the SDK before you can instrument. The API key for your Amplitude project is required.
// Basic initialization with default configurationslet amplitude = Amplitude( apiKey: "YOUR_API_KEY") // Advanced initialization with custom configurationslet amplitude = Amplitude( apiKey: "YOUR_API_KEY", serverZone: .US, instanceName: "default_instance", analyticsConfig: AnalyticsConfig(), experimentConfig: ExperimentPlugin.Config(), sessionReplayConfig: SessionReplayPlugin.Config(), logger: ConsoleLogger())
// Basic initialization with default configurationsAmplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY"]; // Advanced initialization with custom configurationsAmplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY" serverZone:AMPServerZoneUS instanceName:@"default_instance" analyticsConfig:[[AMPAnalyticsConfig alloc] init] experimentConfig:[[AMPExperimentPluginConfig alloc] init] sessionReplayConfig:[[AMPSessionReplayPluginConfig alloc] init] logger:[[AMPConsoleLogger alloc] init]];
The Unified SDK provides a simplified configuration interface for the Analytics SDK. For a complete list of configuration options, see the Analytics SDK documentation.
let analyticsConfig = AnalyticsConfig( flushQueueSize: 30, flushIntervalMillis: 30000, trackingOptions: TrackingOptions().disableTrackCity().disableTrackIpAddress(), minTimeBetweenSessionsMillis: 300000, autocapture: [.sessions, .appLifecycles, .screenViews]) let amplitude = Amplitude( apiKey: "YOUR_API_KEY", analyticsConfig: analyticsConfig)
AMPAnalyticsConfig *analyticsConfig = [[AMPAnalyticsConfig alloc] init];analyticsConfig.flushQueueSize = 30;analyticsConfig.flushIntervalMillis = 30000;[analyticsConfig.trackingOptions disableTrackCity];[analyticsConfig.trackingOptions disableTrackIpAddress];analyticsConfig.minTimeBetweenSessionsMillis = 300000;analyticsConfig.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[ AMPAutocaptureOptions.sessions, AMPAutocaptureOptions.appLifecycles, AMPAutocaptureOptions.screenViews]]; Amplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY" analyticsConfig:analyticsConfig];
The Unified SDK automatically configures the Experiment SDK with sensible defaults. For more advanced configuration options, see the Experiment SDK documentation.
let experimentConfig = ExperimentPlugin.Config( serverUrl: "https://api.lab.amplitude.com", debug: true, fetchTimeoutMillis: 10000) let amplitude = Amplitude( apiKey: "YOUR_API_KEY", experimentConfig: experimentConfig)
AMPExperimentPluginConfig *experimentConfig = [[AMPExperimentPluginConfig alloc] init];experimentConfig.serverUrl = @"https://api.lab.amplitude.com";experimentConfig.debug = YES;experimentConfig.fetchTimeoutMillis = 10000; Amplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY" experimentConfig:experimentConfig];
The Unified SDK automatically configures the Session Replay SDK with sensible defaults. For more advanced configuration options, see the Session Replay SDK documentation.
Session Replay is only available on iOS platforms, not on macOS, tvOS, watchOS, or visionOS.
#if canImport(AmplitudeSessionReplay)let sessionReplayConfig = SessionReplayPlugin.Config( sessionSampleRate: 100, scrollSampleRate: 50) let amplitude = Amplitude( apiKey: "YOUR_API_KEY", sessionReplayConfig: sessionReplayConfig)#endif
#if __has_include(<AmplitudeSessionReplay/AmplitudeSessionReplay.h>)AMPSessionReplayPluginConfig *sessionReplayConfig = [[AMPSessionReplayPluginConfig alloc] init];sessionReplayConfig.sessionSampleRate = 100;sessionReplayConfig.scrollSampleRate = 50; Amplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY" sessionReplayConfig:sessionReplayConfig];#endif
The Unified SDK provides access to all the functionality of the individual SDKs through a single interface.
The Unified SDK exposes all the Analytics SDK functionality directly. For a complete list of methods, see the Analytics SDK documentation.
// Track an eventamplitude.track(eventType: "Button Clicked", eventProperties: ["button_id": "sign_up"]) // Set user propertieslet identify = Identify()identify.set(property: "plan", value: "premium")amplitude.identify(identify: identify) // Set user IDamplitude.setUserId(userId: "user@example.com")
// Track an event[amplitude track:@"Button Clicked" eventProperties:@{@"button_id": @"sign_up"}]; // Set user propertiesAMPIdentify *identify = [AMPIdentify new];[identify set:@"plan" value:@"premium"];[amplitude identify:identify]; // Set user ID[amplitude setUserId:@"user@example.com"];
The Experiment SDK is automatically initialized and configured when you create an Amplitude instance with the Unified SDK. You can access the Experiment client through the experiment
property.
// Fetch variants for the current useramplitude.experiment.fetch().onFetchCompleted { error in if let error = error { print("Error fetching variants: \(error)") return } // Get a variant for a flag let variant = amplitude.experiment.variant("my-flag") print("Variant: \(variant.value)") // Evaluate a flag locally let localVariant = amplitude.experiment.variant("local-flag", fallback: "default") print("Local variant: \(localVariant.value)") // Exposure tracking is automatic when you call variant() // But you can also track exposures manually amplitude.experiment.exposure("my-flag")}
// Fetch variants for the current user[[amplitude.experiment fetch] onFetchCompleted:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"Error fetching variants: %@", error); return; } // Get a variant for a flag ExperimentVariant *variant = [amplitude.experiment variant:@"my-flag"]; NSLog(@"Variant: %@", variant.value); // Evaluate a flag locally ExperimentVariant *localVariant = [amplitude.experiment variant:@"local-flag" fallback:@"default"]; NSLog(@"Local variant: %@", localVariant.value); // Exposure tracking is automatic when you call variant() // But you can also track exposures manually [amplitude.experiment exposure:@"my-flag"];}];
The Session Replay SDK is automatically initialized and configured when you create an Amplitude instance with the Unified SDK on iOS platforms. Session Replay isn't available on macOS, tvOS, watchOS, or visionOS.
#if canImport(AmplitudeSessionReplay)// Session Replay is automatically initialized and configured// You can access the Session Replay client through the sessionReplay property // Start recording a sessionamplitude.sessionReplay?.startRecording() // Stop recordingamplitude.sessionReplay?.stopRecording() // Pause recordingamplitude.sessionReplay?.pauseRecording() // Resume recordingamplitude.sessionReplay?.resumeRecording()#endif
#if __has_include(<AmplitudeSessionReplay/AmplitudeSessionReplay.h>)// Session Replay is automatically initialized and configured// You can access the Session Replay client through the sessionReplay property // Start recording a session[amplitude.sessionReplay startRecording]; // Stop recording[amplitude.sessionReplay stopRecording]; // Pause recording[amplitude.sessionReplay pauseRecording]; // Resume recording[amplitude.sessionReplay resumeRecording];#endif
Follow instructions in this section to enable identity management and other features.
The Unified SDK provides a unified identity management system that synchronizes user identity across all Amplitude products. When you set a user ID or device ID using the Amplitude methods, the changes are automatically propagated to Experiment and Session Replay.
// Set user ID - automatically propagated to all productsamplitude.setUserId(userId: "user@example.com") // Set device ID - automatically propagated to all productsamplitude.setDeviceId(deviceId: "custom-device-id") // Reset user - clears user ID and generates a new device IDamplitude.reset() // Access the current identitylet userId = amplitude.identity.userIdlet deviceId = amplitude.identity.deviceId
// Set user ID - automatically propagated to all products[amplitude setUserId:@"user@example.com"]; // Set device ID - automatically propagated to all products[amplitude setDeviceId:@"custom-device-id"]; // Reset user - clears user ID and generates a new device ID[amplitude reset]; // Access the current identityNSString *userId = amplitude.identity.userId;NSString *deviceId = amplitude.identity.deviceId;
The Unified SDK maintains a cache of user properties that are set with identify operations. This allows you to access the current user properties state at any time.
// Set user propertieslet identify = Identify()identify.set(property: "plan", value: "premium")identify.set(property: "age", value: 25)amplitude.identify(identify: identify) // Access the current user propertieslet userProperties = amplitude.identity.userPropertiesprint("User plan: \(userProperties["plan"] ?? "none")")print("User age: \(userProperties["age"] ?? 0)") // Clear all user propertieslet clearIdentify = Identify()clearIdentify.clearAll()amplitude.identify(identify: clearIdentify)
// Set user propertiesAMPIdentify *identify = [AMPIdentify new];[identify set:@"plan" value:@"premium"];[identify set:@"age" value:@25];[amplitude identify:identify]; // Access the current user propertiesNSDictionary *userProperties = amplitude.identity.userProperties;NSLog(@"User plan: %@", userProperties[@"plan"] ?: @"none");NSLog(@"User age: %@", userProperties[@"age"] ?: @0); // Clear all user propertiesAMPIdentify *clearIdentify = [AMPIdentify new];[clearIdentify clearAll];[amplitude identify:clearIdentify];
To enable debug logging, set the log level to DEBUG
in the Analytics configuration:
let analyticsConfig = AnalyticsConfig( // Other configuration options...) let amplitude = Amplitude( apiKey: "YOUR_API_KEY", analyticsConfig: analyticsConfig, logger: ConsoleLogger(logLevel: LogLevelEnum.DEBUG.rawValue))
AMPAnalyticsConfig *analyticsConfig = [[AMPAnalyticsConfig alloc] init];// Other configuration options... AMPConsoleLogger *logger = [[AMPConsoleLogger alloc] initWithLogLevel:AMPLogLevelDEBUG];Amplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY" analyticsConfig:analyticsConfig logger:logger];
If your implementation of the Unified SDK doesn't work as you expect, make sure you account for the following common issues.
Session Replay is only available on iOS platforms. It isn't available on macOS, tvOS, watchOS, or visionOS. The Unified SDK automatically detects the platform and only initialize Session Replay on iOS.
If events don't appear in Amplitude:
If Experiment flags aren't fetched:
amplitude.experiment.fetch()
If you use the individual Amplitude SDKs separately, follow these steps to migrate to the Unified SDK:
// Analytics SDKlet amplitude = Amplitude(configuration: Configuration( apiKey: "YOUR_API_KEY", flushQueueSize: 30, flushIntervalMillis: 30000)) // Experiment SDKlet experimentClient = Experiment.initialize( apiKey: "YOUR_API_KEY", config: ExperimentConfig( serverUrl: "https://api.lab.amplitude.com" )) // Session Replay SDKlet sessionReplay = SessionReplayPlugin(config: SessionReplayPlugin.Config( sessionSampleRate: 100))amplitude.add(plugin: sessionReplay)
// Analytics SDKAMPConfiguration *configuration = [AMPConfiguration initWithApiKey:@"YOUR_API_KEY"];configuration.flushQueueSize = 30;configuration.flushIntervalMillis = 30000;Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; // Experiment SDKExperimentConfig *experimentConfig = [ExperimentConfig initWithApiKey:@"YOUR_API_KEY"];experimentConfig.serverUrl = @"https://api.lab.amplitude.com";ExperimentClient *experimentClient = [Experiment initializeWithApiKey:@"YOUR_API_KEY" config:experimentConfig]; // Session Replay SDKAMPSessionReplayPluginConfig *sessionReplayConfig = [[AMPSessionReplayPluginConfig alloc] init];sessionReplayConfig.sessionSampleRate = 100;AMPSessionReplayPlugin *sessionReplay = [[AMPSessionReplayPlugin alloc] initWithConfig:sessionReplayConfig];[amplitude add:sessionReplay];
let analyticsConfig = AnalyticsConfig( flushQueueSize: 30, flushIntervalMillis: 30000) let experimentConfig = ExperimentPlugin.Config( serverUrl: "https://api.lab.amplitude.com") let sessionReplayConfig = SessionReplayPlugin.Config( sessionSampleRate: 100) let amplitude = Amplitude( apiKey: "YOUR_API_KEY", analyticsConfig: analyticsConfig, experimentConfig: experimentConfig, sessionReplayConfig: sessionReplayConfig)
AMPAnalyticsConfig *analyticsConfig = [[AMPAnalyticsConfig alloc] init];analyticsConfig.flushQueueSize = 30;analyticsConfig.flushIntervalMillis = 30000; AMPExperimentPluginConfig *experimentConfig = [[AMPExperimentPluginConfig alloc] init];experimentConfig.serverUrl = @"https://api.lab.amplitude.com"; AMPSessionReplayPluginConfig *sessionReplayConfig = [[AMPSessionReplayPluginConfig alloc] init];sessionReplayConfig.sessionSampleRate = 100; Amplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY" analyticsConfig:analyticsConfig experimentConfig:experimentConfig sessionReplayConfig:sessionReplayConfig];
July 23rd, 2024
Need help? Contact Support
Visit Amplitude.com
Have a look at the Amplitude Blog
Learn more at Amplitude Academy
© 2025 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.