---
title: Instrument and configure the Unified SDK for Swift
description: "Configure Analytics, Feature Experiment, and Session Replay in the Amplitude Unified SDK for Swift, fetch variants, control recording, share identity across products, and migrate from the individual SDKs."
product: analytics
lang: en
last_updated: 2026-11-05
token_estimate: 3342
---
# Instrument and configure the Unified SDK for Swift

This guide covers the tasks specific to the Unified SDK for Swift (`AmplitudeUnified`): configuring each product, using Feature Experiment and Session Replay, sharing identity, and migrating from the individual SDKs. Tracking events, identifying users, autocapture, and upload behavior come from the bundled iOS Swift SDK and work the same way. For those tasks, go to [Instrument and configure the iOS Swift SDK](https://amplitude.com/docs/sdks/analytics/ios/ios-swift-sdk/instrument-and-configure). For signatures, go to the [Unified SDK for Swift reference](https://amplitude.com/docs/sdks/analytics/ios/unified-sdk/reference). For changes between versions, go to the [`AmplitudeUnified` changelog](https://github.com/amplitude/AmplitudeUnified-Swift/blob/main/CHANGELOG.md).

> For AI agents: a documentation index is available at [/docs/llms.txt](/docs/llms.txt). Append `.md` to any page URL for markdown, or send `Accept: text/markdown`.

## Configure each product

### How the initializer sets up each product

The Unified [initializer](https://amplitude.com/docs/sdks/analytics/ios/unified-sdk/reference#init) runs these steps in order:

1. Creates Analytics (the iOS Swift SDK) from `apiKey`, `serverZone`, `instanceName`, `analyticsConfig`, and `logger`.
2. On iOS, adds the Session Replay plugin with `sessionReplayConfig`.
3. Adds the Feature Experiment plugin with `experimentConfig`.
4. Adds a plugin that prefixes each event's `library` field with `amplitude-swift-unified/0.0.0`.

Feature Experiment and Session Replay read `serverZone`, `instanceName`, and the API key from Analytics. With `serverZone: .EU`, Analytics uploads to `api.eu.amplitude.com`. Feature Experiment fetches from `api.lab.eu.amplitude.com`, as long as you leave the Experiment `serverUrl` and `flagsServerUrl` at their defaults.

### Pass options to each product

Each argument accepts that product's configuration. Leave out any argument to use its defaults.

#### Swift

```swift
let amplitude = Amplitude(
    apiKey: "YOUR_API_KEY",
    serverZone: .EU,
    analyticsConfig: AnalyticsConfig(
        flushQueueSize: 50,
        trackingOptions: TrackingOptions().disableTrackIpAddress().disableTrackCarrier(),
        minTimeBetweenSessionsMillis: 300000,
        autocapture: [.sessions, .appLifecycles, .screenViews]
    ),
    experimentConfig: ExperimentPlugin.Config(
        deploymentKey: "YOUR_CLIENT_DEPLOYMENT_KEY",
        fetchTimeoutMillis: 5000
    ),
    sessionReplayConfig: SessionReplayPlugin.Config(sampleRate: 0.1)
)
```

#### Objective-C

```objc
AMPAnalyticsConfig *analyticsConfig = [[AMPAnalyticsConfig alloc] init];
analyticsConfig.flushQueueSize = 50;
[analyticsConfig.trackingOptions disableTrackCarrier];
[analyticsConfig.trackingOptions disableTrackIpAddress];
analyticsConfig.minTimeBetweenSessionsMillis = 300000;
analyticsConfig.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[
    AMPAutocaptureOptions.sessions,
    AMPAutocaptureOptions.appLifecycles,
    AMPAutocaptureOptions.screenViews
]];

ExperimentPluginConfig *experimentConfig = [[ExperimentPluginConfig alloc] init];
experimentConfig.deploymentKey = @"YOUR_CLIENT_DEPLOYMENT_KEY";
experimentConfig.fetchTimeoutMillis = 5000;

AMPSessionReplayPluginConfig *sessionReplayConfig =
    [[AMPSessionReplayPluginConfig alloc] initWithSampleRate:0.1
                                                   maskLevel:MaskLevelMedium
                                                     quality:AMPSessionReplayQualityProfileHigh
                                          enableRemoteConfig:YES
                                             webviewMappings:@{}
                                                   autoStart:YES
                                             captureWebViews:NO
                                            recordLogOptions:[[RecordLogOptions alloc] initWithLogCountThreshold:1000 maxMessageLength:2000]
                                                uploadConfig:[[AMPSessionReplayUploadConfig alloc] initWithDisableMeteredUploads:NO]];

Amplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY"
                                              serverZone:AMPServerZoneEU
                                            instanceName:@"$default_instance"
                                         analyticsConfig:analyticsConfig
                                        experimentConfig:experimentConfig
                                     sessionReplayConfig:sessionReplayConfig
                                                  logger:nil];
```

`AMPAnalyticsConfig` and `ExperimentPluginConfig` have settable properties. `AMPSessionReplayPluginConfig` is read-only, so set its options through its initializer, which takes every argument.

| Argument | Accepts |
| --- | --- |
| `analyticsConfig` | A subset of the [iOS Swift SDK options](https://amplitude.com/docs/sdks/analytics/ios/ios-swift-sdk/reference#configuration-options). Go to [AnalyticsConfig](https://amplitude.com/docs/sdks/analytics/ios/unified-sdk/reference#analyticsconfig). |
| `experimentConfig` | Feature Experiment options. Go to [ExperimentPlugin.Config](https://amplitude.com/docs/sdks/analytics/ios/unified-sdk/reference#experimentpluginconfig). |
| `sessionReplayConfig` | Session Replay options, iOS only. Go to [SessionReplayPlugin.Config](https://amplitude.com/docs/sdks/analytics/ios/unified-sdk/reference#sessionreplaypluginconfig). |

Swift requires the arguments of `AnalyticsConfig` and `ExperimentPlugin.Config` in their declared order. If Xcode reports `argument '...' must precede argument '...'`, check the order in the reference.

### Set options that AnalyticsConfig doesn't include

`AnalyticsConfig` doesn't include every iOS Swift SDK option. Set opt-out and offline mode on the instance after you create it:

```swift
amplitude.configuration.offline = true
amplitude.optOut = true
```

You can't set network request tracking (`networkTrackingOptions`) from Swift through the Unified SDK, because its setter isn't public. In Objective-C, set `analyticsConfig.networkTrackingOptions` before you initialize. For the log level, go to [Turn on debug logging](https://amplitude.com/docs/sdks/analytics/ios/unified-sdk/verify-events#turn-on-debug-logging).

## Use Feature Experiment

### Fetch flags and read a variant

The Feature Experiment client doesn't fetch flags when you create the instance. Call `fetch()` and wait for its completion before you read a variant.

#### Swift

```swift
amplitude.experiment?.fetch(user: nil) { client, error in
    if let error {
        print("Fetch failed: \(error)")
        return
    }
    let variant = client.variant("checkout-redesign")
    if variant.value == "treatment" {
        // Show the new checkout.
    }
}
```

#### Objective-C

```objc
[amplitude.experiment fetchWithUser:nil completion:^(id<ExperimentClient> client, NSError *error) {
    if (error != nil) {
        NSLog(@"Fetch failed: %@", error);
        return;
    }
    Variant *variant = [client variant:@"checkout-redesign"];
    if ([variant.value isEqualToString:@"treatment"]) {
        // Show the new checkout.
    }
}];
```

Pass `nil` as the user. The plugin builds the user from Analytics: the user ID, device ID, and user properties at the time of the fetch. Call `setUserId()` before `fetch()` when you know the user. The plugin doesn't fetch again when the identity changes, unless you set `automaticFetchOnAmplitudeIdentityChange` to `true`.

For the client's other methods, such as `all()`, `clear()`, and `start()`, go to the [Experiment iOS SDK](https://amplitude.com/docs/sdks/experiment-sdks/experiment-ios).

### Track exposures

`variant()` tracks a `$exposure` event through Analytics when the flag has a variant for the user. It tracks nothing when it returns a fallback. To track an exposure yourself, turn off `automaticExposureTracking` and call `exposure(key:)` when the user sees the variant:

```swift
let amplitude = Amplitude(
    apiKey: "YOUR_API_KEY",
    experimentConfig: ExperimentPlugin.Config(automaticExposureTracking: false)
)

// Later, after fetch() completes and the user sees the variant:
amplitude.experiment?.exposure(key: "checkout-redesign")
```

The `$exposure` event has `flag_key` and `variant` event properties.

### Set the deployment key

Set `deploymentKey` to a client deployment key from Amplitude Experiment. If you omit it, the plugin uses your project API key as the deployment key.

## Use Session Replay

The Unified SDK includes Session Replay on iOS only. On macOS, tvOS, watchOS, and visionOS, the package doesn't include Session Replay, and the initializer has no `sessionReplayConfig` argument. Wrap Session Replay code in `#if canImport(AmplitudeSessionReplay)` if your app builds for more than one platform.

### Choose a sample rate

Session Replay records nothing by default, because `sampleRate` defaults to `0.0`. Set a value between `0` and `1`: `1.0` records every session, and `0.1` records about one session in ten. Use `1.0` while you test, then lower it before production.

```swift
#if canImport(AmplitudeSessionReplay)
let amplitude = Amplitude(
    apiKey: "YOUR_API_KEY",
    sessionReplayConfig: SessionReplayPlugin.Config(sampleRate: 0.1)
)
#endif
```

When `enableRemoteConfig` is `true` (the default), Session Replay settings from Amplitude, such as the masking level, take precedence over local values.

### Control recording from code

`amplitude.sessionReplay` returns the Session Replay client on iOS:

#### Swift

```swift
amplitude.sessionReplay?.stop()  // Pause recording, for example on a screen with sensitive data.
amplitude.sessionReplay?.start() // Resume recording.
```

#### Objective-C

```objc
AMPSessionReplay *sessionReplay = amplitude.sessionReplay;
[sessionReplay stop];
[sessionReplay start];
```

`start()` still respects the sample rate and remote configuration. For masking, privacy, and the other options, go to [Session Replay iOS plugin](https://amplitude.com/docs/sdks/session-replay/session-replay-ios-plugin).

## Identity and user properties

### How identity reaches each product

Analytics owns the user ID, device ID, and user properties. Feature Experiment and Session Replay read them from Analytics, so set identity once through the Analytics methods:

```swift
amplitude.setUserId(userId: "user@example.com")
amplitude.setDeviceId(deviceId: "custom-device-id")

let identify = Identify()
identify.set(property: "plan", value: "premium")
amplitude.identify(identify: identify)
```

The next Feature Experiment `fetch()` sends the new user ID, device ID, and user properties. Session Replay records against the Analytics device ID and session ID.

### Read the current identity

`amplitude.identity` returns the current user ID, device ID, and user properties. `identify()` updates `userProperties` right away, before the event uploads.

```swift
let identity = amplitude.identity
print(identity.userId ?? "none", identity.deviceId ?? "none")
print(identity.userProperties["plan"] ?? "none") // premium
```

In Objective-C, `identity` isn't available. Call `getUserId` and `getDeviceId` instead.

An `Identify` with `clearAll()` empties `userProperties`.

### Reset when a user logs out

`reset()` clears the user ID and user properties, then chooses a device ID the same way the SDK does on first launch. With IDFV tracking on, the default on iOS, the device ID returns to the IDFV, so it may not change. For how to get a new random device ID, go to [Reset when a user logs out](https://amplitude.com/docs/sdks/analytics/ios/ios-swift-sdk/instrument-and-configure#reset-when-a-user-logs-out) in the iOS Swift SDK.

## Migrate from the individual SDKs

If your app uses `AmplitudeSwift`, `AmplitudeExperiment`, and `AmplitudeSessionReplay` separately:

1. Add `AmplitudeUnified`, then remove the three individual packages.
2. Replace `Amplitude(configuration:)`, `Experiment.initialize(apiKey:config:)`, and `amplitude.add(plugin: SessionReplayPlugin(...))` with the Unified initializer.
3. Move each `Configuration` option into `AnalyticsConfig`. For options `AnalyticsConfig` doesn't include, go to [Set options that AnalyticsConfig doesn't include](#set-options-that-analyticsconfig-doesnt-include).
4. Replace your Experiment client variable with `amplitude.experiment`. The plugin builds the Experiment user from Analytics, so remove any user provider you set.

Before:

```swift
let amplitude = Amplitude(configuration: Configuration(
    apiKey: "YOUR_API_KEY",
    flushQueueSize: 50
))

let experiment = Experiment.initialize(
    apiKey: "YOUR_CLIENT_DEPLOYMENT_KEY",
    config: ExperimentConfigBuilder().build()
)

amplitude.add(plugin: SessionReplayPlugin(config: SessionReplayPlugin.Config(sampleRate: 0.1)))
```

After:

```swift
let amplitude = Amplitude(
    apiKey: "YOUR_API_KEY",
    analyticsConfig: AnalyticsConfig(flushQueueSize: 50),
    experimentConfig: ExperimentPlugin.Config(deploymentKey: "YOUR_CLIENT_DEPLOYMENT_KEY"),
    sessionReplayConfig: SessionReplayPlugin.Config(sampleRate: 0.1)
)

let experiment = amplitude.experiment
```

The Unified SDK reads stored events and identity from the same location as `AmplitudeSwift` when you keep the same `instanceName`, so users keep their device ID after the migration.

