Unified SDK for Swift
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:
Install the SDK
Add the dependency to your
Podfile:bashpod 'AmplitudeUnified', '~> 0.0.0'Run
pod installin the project directory.
Initialize the SDK
Initialize the SDK before you instrument. Provide the API key for your Amplitude project.
// 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()
)
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.
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
)
Experiment configuration
The Unified SDK configures the Experiment SDK with sensible defaults. For more advanced configuration options, refer to 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
)
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.
Session Replay is available only on iOS, 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
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.
// 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")
Experiment
The Unified SDK initializes and configures the Experiment SDK when you create an Amplitude instance. Access the Experiment client through the experiment property.
// 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")
}
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.
#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
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.
// 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
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.
// 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)
Debugging
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)
)
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:
- Check that you use the correct API key.
- Verify that the device has an internet connection.
- Wait long enough for events to flush (the default time is 30 seconds).
- Check the logs for error messages.
Experiment flags don't fetch
If Experiment flags don't fetch:
- Ensure you've called
amplitude.experiment.fetch(). - Check that the user ID or device ID is set correctly.
- Verify that you configure the flags correctly in the Amplitude Experiment dashboard.
- 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:
- Add the Unified SDK dependency to your project.
- Remove the individual SDK dependencies (AmplitudeSwift, Experiment, AmplitudeSessionReplay).
- Replace your initialization code with the Unified SDK initialization.
- Update your API calls to use the Unified SDK interface.
Before migration
// 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)
After migration
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
)
Was this helpful?