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. For signatures, go to the Unified SDK for Swift reference. For changes between versions, go to the AmplitudeUnified changelog.

Configure each product

How the initializer sets up each product

The Unified initializer 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
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)
)

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.

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
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.
    }
}

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.

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
amplitude.sessionReplay?.stop()  // Pause recording, for example on a screen with sensitive data.
amplitude.sessionReplay?.start() // Resume recording.

start() still respects the sample rate and remote configuration. For masking, privacy, and the other options, go to 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 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.
  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.

이 내용이 도움이 되었나요?

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

이 페이지에서