
This is the official documentation for the Amplitude Unified SDK for Swift.

The Unified SDK wraps Amplitude's existing SDKs and provides a simplified interface for using multiple Amplitude products together. It includes:

- [Analytics SDK (AmplitudeSwift)](/docs/sdks/analytics/ios/ios-swift-sdk).
- [Experiment SDK](/docs/sdks/experiment-sdks/experiment-ios).
- [Session Replay SDK](/docs/session-replay/session-replay-ios-plugin) (iOS only).

## Install the SDK

{% tabs tabs="CocoaPods, Swift Package Manager" %}
{% tab name="CocoaPods" %}

1. Add the dependency to your `Podfile`:

   ```bash
   pod 'AmplitudeUnified', '~> 0.0.0'
   ```

2. Run `pod install` in the project directory.
{% /tab %}
{% tab name="Swift Package Manager" %}
3. Navigate to *File > Swift Package Manager > Add Package Dependency*. A dialog opens that lets you add a package dependency.
4. Enter the URL `https://github.com/amplitude/AmplitudeUnified-Swift` in the search bar.
5. Xcode resolves to the latest version automatically. You can also select a specific version.
6. Click **Next** to confirm the package as a dependency.
7. Build your project to confirm the package integrates correctly.
{% /tab %}
{% /tabs %}

## Initialize the SDK

Initialize the SDK before you instrument. Provide the API key for your Amplitude project.

{% code-group %}
```swift Swift
// Basic initialization with default configurations
let amplitude = Amplitude(
    apiKey: "YOUR_API_KEY"
)

// Advanced initialization with custom configurations
let amplitude = Amplitude(
    apiKey: "YOUR_API_KEY",
    serverZone: .US,
    instanceName: "default_instance",
    analyticsConfig: AnalyticsConfig(),
    experimentConfig: ExperimentPlugin.Config(),
    sessionReplayConfig: SessionReplayPlugin.Config(),
    logger: ConsoleLogger()
)
```

```objc Obj-C
// Basic initialization with default configurations
Amplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY"];

// Basic initialization with server zone
Amplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY"
                                              serverZone:AMPServerZoneUS];

// Advanced initialization with custom configurations
Amplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY"
                                              serverZone:AMPServerZoneUS
                                           instanceName:@"default_instance"
                                                 analyticsConfig:[[AMPAnalyticsConfig alloc] init]
                                                experimentConfig:[[ExperimentPluginConfig alloc] init]
                                            sessionReplayConfig:[[AMPSessionReplayPluginConfig alloc] init]
                                                         logger:nil];
```
{% /code-group %}

## Configure the SDK

### Analytics configuration

The Unified SDK provides a simplified configuration interface for the Analytics SDK. For a complete list of configuration options, refer to the [Analytics SDK documentation](/docs/sdks/analytics/ios/ios-swift-sdk#configure-the-sdk).

{% code-group %}
```swift Swift
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
)
```

```objc Obj-C
AMPAnalyticsConfig *analyticsConfig = [[AMPAnalyticsConfig alloc] init];
analyticsConfig.flushQueueSize = 30;
analyticsConfig.flushIntervalMillis = 30000;
[analyticsConfig.trackingOptions disableTrackCity];
[analyticsConfig.trackingOptions disableTrackIpAddress];
analyticsConfig.minTimeBetweenSessionsMillis = 300000;
analyticsConfig.autocapture = AMPAutocaptureOptions.all;
analyticsConfig.migrateLegacyData = YES;
analyticsConfig.enableAutoCaptureRemoteConfig = YES;
]];
Amplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY"
                                         analyticsConfig:analyticsConfig];
```
{% /code-group %}

### Experiment configuration

The Unified SDK configures the Experiment SDK with sensible defaults. For more advanced configuration options, refer to the [Experiment SDK documentation](/docs/sdks/experiment-sdks/experiment-ios).

{% code-group %}
```swift Swift
let experimentConfig = ExperimentPlugin.Config(
    serverUrl: "https://api.lab.amplitude.com",
    debug: true,
    fetchTimeoutMillis: 10000
)

let amplitude = Amplitude(
    apiKey: "YOUR_API_KEY",
    experimentConfig: experimentConfig
)
```

```objc Obj-C
ExperimentPluginConfig *experimentConfig = [[ExperimentPluginConfig 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];
```
{% /code-group %}

### Session Replay configuration

The Unified SDK configures the Session Replay SDK with sensible defaults. For more advanced configuration options, refer to the [Session Replay SDK documentation](/docs/session-replay/session-replay-ios-plugin).

{% callout type="note" heading="" %}
Session Replay is available only on iOS, not on macOS, tvOS, watchOS, or visionOS.
{% /callout %}

{% code-group %}
```swift Swift
#if canImport(AmplitudeSessionReplay)
let sessionReplayConfig = SessionReplayPlugin.Config(
    sessionSampleRate: 100,
    scrollSampleRate: 50
)

let amplitude = Amplitude(
    apiKey: "YOUR_API_KEY",
    sessionReplayConfig: sessionReplayConfig
)
#endif
```

```objc Obj-C
#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
```
{% /code-group %}

## Use the SDK

The Unified SDK provides access to all functionality of the individual SDKs through a single interface.

### Analytics

The Unified SDK exposes all Analytics SDK functionality directly. For a complete list of methods, refer to the [Analytics SDK documentation](/docs/sdks/analytics/ios/ios-swift-sdk).

{% code-group %}
```swift Swift
// Track an event
amplitude.track(eventType: "Button Clicked", eventProperties: ["button_id": "sign_up"])

// Set user properties
let identify = Identify()
identify.set(property: "plan", value: "premium")
amplitude.identify(identify: identify)

// Set user ID
amplitude.setUserId(userId: "user@example.com")
```

```objc Obj-C
// Track an event
[amplitude track:@"Button Clicked" eventProperties:@{@"button_id": @"sign_up"}];

// Set user properties
AMPIdentify *identify = [[AMPIdentify alloc] init];
[identify set:@"plan" value:@"premium"];
[amplitude identify:identify];

// Set user ID
[amplitude setUserId:@"user@example.com"];
```
{% /code-group %}

### Experiment

The Unified SDK initializes and configures the Experiment SDK when you create an Amplitude instance. Access the Experiment client through the `experiment` property.

{% code-group %}
```swift Swift
// Fetch variants for the current user
amplitude.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")
}
```

```objc Obj-C
// Access the experiment client
ExperimentClient *experimentClient = amplitude.experiment;

// Fetch variants for the current user
[[experimentClient fetch] onFetchCompleted:^(NSError * _Nullable error) {
    if (error != nil) {
        NSLog(@"Error fetching variants: %@", error);
        return;
    }

    // Get a variant for a flag
    ExperimentVariant *variant = [experimentClient variant:@"my-flag"];
    NSLog(@"Variant: %@", variant.value);

    // Evaluate a flag locally
    ExperimentVariant *localVariant = [experimentClient 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
    [experimentClient exposure:@"my-flag"];
}];
```
{% /code-group %}

### Session Replay

The Unified SDK initializes and configures the Session Replay SDK when you create an Amplitude instance on iOS. Session Replay isn't available on macOS, tvOS, watchOS, or visionOS.

{% code-group %}
```swift Swift
#if canImport(AmplitudeSessionReplay)
// 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
```

```objc Obj-C
#if __has_include(<AmplitudeSessionReplay/AmplitudeSessionReplay.h>)
// Session Replay is automatically initialized and configured
// You can access the Session Replay client through the sessionReplay property
SessionReplay *sessionReplay = amplitude.sessionReplay;

// Start recording a session
[sessionReplay startRecording];

// Stop recording
[sessionReplay stopRecording];

// Pause recording
[sessionReplay pauseRecording];

// Resume recording
[sessionReplay resumeRecording];
#endif
```
{% /code-group %}

## Advanced topics

Follow instructions in this section to enable identity management and other features.

### Identity management

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 SDK propagates the changes to Experiment and Session Replay.

{% code-group %}
```swift Swift
// Set user ID - automatically propagated to all products
amplitude.setUserId(userId: "user@example.com")

// Set device ID - automatically propagated to all products
amplitude.setDeviceId(deviceId: "custom-device-id")

// Reset user - clears user ID and generates a new device ID
amplitude.reset()

// Access the current identity
let userId = amplitude.identity.userId
let deviceId = amplitude.identity.deviceId
```

```objc Obj-C
// 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 identity
NSString *userId = amplitude.identity.userId;
NSString *deviceId = amplitude.identity.deviceId;
```
{% /code-group %}

### User properties

The Unified SDK maintains a cache of user properties that identify operations set. The cache lets you access the current user properties state at any time.

{% code-group %}
```swift Swift
// Set user properties
let identify = Identify()
identify.set(property: "plan", value: "premium")
identify.set(property: "age", value: 25)
amplitude.identify(identify: identify)

// Access the current user properties
let userProperties = amplitude.identity.userProperties
print("User plan: \(userProperties["plan"] ?? "none")")
print("User age: \(userProperties["age"] ?? 0)")

// Clear all user properties
let clearIdentify = Identify()
clearIdentify.clearAll()
amplitude.identify(identify: clearIdentify)
```
{% /code-group %}

## Debugging

To enable debug logging, set the log level to `DEBUG` in the Analytics configuration:

{% code-group %}
```swift Swift
let analyticsConfig = AnalyticsConfig(
    // Other configuration options...
)

let amplitude = Amplitude(
    apiKey: "YOUR_API_KEY",
    analyticsConfig: analyticsConfig,
    logger: ConsoleLogger(logLevel: LogLevelEnum.DEBUG.rawValue)
)
```

```objc Obj-C
AMPAnalyticsConfig *analyticsConfig = [[AMPAnalyticsConfig alloc] init];
// Other configuration options...

Amplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY"
                                         analyticsConfig:analyticsConfig
                                                  logger:^(NSInteger logLevel, NSString *logMessage) {
        NSLog(@"%@", logMessage);
    }];
```
{% /code-group %}

## Common issues

If your implementation of the Unified SDK doesn't work as you expect, account for the following common issues.

### Session Replay doesn't work on non-iOS platforms

Session Replay is available only on iOS. It isn't available on macOS, tvOS, watchOS, or visionOS. The Unified SDK detects the platform and initializes Session Replay only on iOS.

### Events don't appear in Amplitude

If events don't appear in Amplitude:

1. Check that you use the correct API key.
2. Verify that the device has an internet connection.
3. Wait long enough for events to flush (the default time is 30 seconds).
4. Check the logs for error messages.

### Experiment flags don't fetch

If Experiment flags don't fetch:

1. Ensure you've called `amplitude.experiment.fetch()`.
2. Check that the user ID or device ID is set correctly.
3. Verify that you configure the flags correctly in the Amplitude Experiment dashboard.
4. Check the logs for error messages from the Experiment SDK.

## Migration guide

If you use the individual Amplitude SDKs separately, follow these steps to migrate to the Unified SDK:

1. Add the Unified SDK dependency to your project.
2. Remove the individual SDK dependencies (AmplitudeSwift, Experiment, AmplitudeSessionReplay).
3. Replace your initialization code with the Unified SDK initialization.
4. Update your API calls to use the Unified SDK interface.

### Before migration

{% code-group %}
```swift Swift
// Analytics SDK
let amplitude = Amplitude(configuration: Configuration(
    apiKey: "YOUR_API_KEY",
    flushQueueSize: 30,
    flushIntervalMillis: 30000
))

// Experiment SDK
let experimentClient = Experiment.initialize(
    apiKey: "YOUR_API_KEY",
    config: ExperimentConfig(
        serverUrl: "https://api.lab.amplitude.com"
    )
)

// Session Replay SDK
let sessionReplay = SessionReplayPlugin(config: SessionReplayPlugin.Config(
    sessionSampleRate: 100
))
amplitude.add(plugin: sessionReplay)
```

```objc Obj-C
// Analytics SDK
AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:@"YOUR_API_KEY"];
configuration.flushQueueSize = 30;
configuration.flushIntervalMillis = 30000;
Amplitude *amplitude = [Amplitude initWithConfiguration:configuration];

// Experiment SDK
ExperimentConfig *experimentConfig = [ExperimentConfig initWithApiKey:@"YOUR_API_KEY"];
experimentConfig.serverUrl = @"https://api.lab.amplitude.com";
ExperimentClient *experimentClient = [Experiment initializeWithApiKey:@"YOUR_API_KEY" config:experimentConfig];

// Session Replay SDK
AMPSessionReplayPluginConfig *sessionReplayConfig = [[AMPSessionReplayPluginConfig alloc] init];
sessionReplayConfig.sessionSampleRate = 100;
AMPSessionReplayPlugin *sessionReplay = [[AMPSessionReplayPlugin alloc] initWithConfig:sessionReplayConfig];
[amplitude add:sessionReplay];
```
{% /code-group %}

### After migration

{% code-group %}
```swift Swift
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
)
```

```objc Obj-C
AMPAnalyticsConfig *analyticsConfig = [[AMPAnalyticsConfig alloc] init];
analyticsConfig.flushQueueSize = 30;
analyticsConfig.flushIntervalMillis = 30000;

ExperimentPluginConfig *experimentConfig = [[ExperimentPluginConfig 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"
                                            serverZone:AMPServerZoneUS
                                          instanceName:@"default"
                                       analyticsConfig:analyticsConfig
                                      experimentConfig:experimentConfig
                                   sessionReplayConfig:sessionReplayConfig
                                                logger:nil];
```
{% /code-group %}
