Unified SDK for Swift reference
このページはまだあなたの言語に翻訳されていません。 現在取り組んでいますので、後でもう一度確認してください。
This reference documents every public export of AmplitudeUnified and every option you can pass to its initializers, verified against version 0.0.4. That version, resolved with Swift Package Manager, used iOS Swift SDK 1.19.4 (AmplitudeSwift), Experiment iOS SDK 1.20.3, and Session Replay 0.17.0. Every analytics method behaves as the iOS Swift SDK reference describes. For changes between versions, go to the AmplitudeUnified changelog.
import AmplitudeUnified
AmplitudeUnified re-exports AmplitudeSwift, AmplitudeCore, the Experiment module, and, on iOS, AmplitudeSessionReplay. The Unified SDK doesn't add a new client class. It adds an initializer to the iOS Swift SDK's Amplitude class, so you can use every Amplitude method and property.
Exports
| Export | Description |
|---|---|
Amplitude(apiKey:...), AnalyticsConfig | Specific to the Unified SDK. Documented on this page. |
experiment, sessionReplay | Properties that the Experiment and Session Replay modules add to Amplitude. Documented on this page. |
ExperimentPlugin.Config, SessionReplayPlugin.Config | Plugin configurations from the Experiment and Session Replay modules. Documented on this page. |
track, identify, setUserId, setDeviceId, reset, flush, add, identity, and the other Amplitude members | The iOS Swift SDK methods. Go to the iOS Swift SDK reference. |
ObjCAmplitude initializers, AMPAnalyticsConfig | Objective-C interface. Go to Objective-C initializers and AMPAnalyticsConfig. |
Setup
init
Creates Analytics, then adds the Session Replay plugin (iOS only), the Feature Experiment plugin, and the plugin that marks events as sent by the Unified SDK.
On iOS:
convenience init(
apiKey: String,
serverZone: AmplitudeCore.ServerZone = .US,
instanceName: String = "$default_instance",
analyticsConfig: AnalyticsConfig = .init(),
experimentConfig: ExperimentPlugin.Config = .init(),
sessionReplayConfig: SessionReplayPlugin.Config = .init(),
logger: any Logger = ConsoleLogger()
)
On macOS, tvOS, watchOS, and visionOS, the initializer is the same without sessionReplayConfig.
| Parameter | Type | Description |
|---|---|---|
apiKey | String | Your Amplitude project API key. Feature Experiment also uses it as the deployment key unless you set deploymentKey. |
serverZone | ServerZone | Optional. .US or .EU. Analytics, Feature Experiment, and Session Replay all use it. Default .US. |
instanceName | String | Optional. The storage namespace for events and identity. Use a distinct name for each instance. Default "$default_instance". |
analyticsConfig | AnalyticsConfig | Optional. Go to AnalyticsConfig. |
experimentConfig | ExperimentPlugin.Config | Optional. Go to ExperimentPlugin.Config. |
sessionReplayConfig | SessionReplayPlugin.Config | Optional, iOS only. Go to SessionReplayPlugin.Config. With the default, Session Replay doesn't record. |
logger | any Logger | Optional. Receives the SDK's log messages. The SDK sets its logLevel to warn during initialization, whatever level you pass. Default ConsoleLogger(). |
let amplitude = Amplitude(
apiKey: "YOUR_API_KEY",
serverZone: .EU,
sessionReplayConfig: SessionReplayPlugin.Config(sampleRate: 0.1)
)
To raise the log level after initialization, go to Turn on debug logging.
Objective-C initializers
The Objective-C class is Amplitude. Import Experiment (AmplitudeExperiment with CocoaPods) and AmplitudeSessionReplay as well as AmplitudeUnified. Objective-C has three initializers, and no shorter forms:
| Initializer | Description |
|---|---|
initWithApiKey: | Uses the defaults for every option. |
initWithApiKey:serverZone: | In version 0.0.4, ignores serverZone and uses AMPServerZoneUS. For EU projects, use the full initializer. |
initWithApiKey:serverZone:instanceName:analyticsConfig:experimentConfig:sessionReplayConfig:logger: | Sets every option. Off iOS, the selector has no sessionReplayConfig: part. logger is a void (^)(NSInteger logLevel, NSString *logMessage) block, or nil. |
The Objective-C initializers require version 0.0.2 or later.
Amplitude *amplitude = [[Amplitude alloc] initWithApiKey:@"YOUR_API_KEY"];
experiment
Returns the Feature Experiment client.
var experiment: ExperimentClient? { get }
func experiment(apiKey: String?) -> ExperimentClient?
The property returns nil when the instance has more than one Feature Experiment plugin. In that case, call experiment(apiKey:) with the plugin's deployment key, or nil for the plugin that uses the project API key. The client is the Experiment iOS SDK client. It doesn't fetch flags at initialization. Call fetch(user:completion:) before variant().
amplitude.experiment?.fetch(user: nil) { client, error in
let variant = client.variant("checkout-redesign")
}
| Method | Description |
|---|---|
fetch(user:completion:) | Fetches variants for the Analytics user. Pass nil as the user. |
variant(_:), variant(_:fallback:) | Returns the variant for a flag key, and tracks $exposure when the variant comes from a fetch. |
exposure(key:) | Tracks $exposure for the flag's current variant. |
all(), clear(), start(_:completion:), stop() | Go to the Experiment iOS SDK. |
sessionReplay
Returns the Session Replay client. iOS only.
var sessionReplay: SessionReplay? { get }
In Objective-C, the type is AMPSessionReplay.
| Member | Description |
|---|---|
start() | Starts or resumes recording. Recording still respects the sample rate and remote configuration. |
stop() | Pauses recording. Call start() to resume. |
flush() | Uploads recorded data now. |
sessionId, deviceId | The session ID and device ID that Session Replay records against. |
sampleRate, maskLevel | Read-only. The values in effect. |
optOut | Turns off recording for this device while true. |
amplitude.sessionReplay?.stop()
AnalyticsConfig
The Analytics options for the Swift initializer. Swift requires the arguments in the order this table lists. Each option maps to the iOS Swift SDK Configuration option of the same name. For behavior, go to Configuration options in the iOS Swift SDK.
| Option | Type | Default | Description |
|---|---|---|---|
flushQueueSize | Int | 30 | Events tracked since the last upload that trigger an upload. |
flushIntervalMillis | Int | 30000 | The time between uploads, in milliseconds. |
storageProvider | (any Storage)? | nil, file and UserDefaults storage | Where the SDK stores events and identity. |
identifyStorageProvider | (any Storage)? | nil, the SDK's file storage | Where the SDK stores held set-only identify events. |
minIDLength | Int? | nil | The minimum accepted length of user and device IDs. With nil, Amplitude enforces 5. Maps to minIdLength. |
partnerID | String? | nil | The partner ID. Maps to partnerId. |
callback | EventCallback? | nil | Called with (event, code, message) after each upload attempt that the server answers. |
flushMaxRetries | Int | 6 | Consecutive failed uploads after which the SDK goes offline and stops uploading. |
useBatch | Bool | false | Uploads to the Batch API instead of the HTTP V2 API. |
serverURL | String? | nil, the endpoint for serverZone | A custom upload URL, such as a proxy. Maps to serverUrl. |
plan | Plan? | nil | The tracking plan information to attach to events. |
ingestionMetadata | IngestionMetadata? | nil | The ingestion metadata to attach to events. |
trackingOptions | TrackingOptions | TrackingOptions(), every property on | The device properties the SDK collects. |
enableCoppaControl | Bool | false | Turns off IDFV, IP address, city, and IDFA tracking. |
flushEventsOnClose | Bool | true | Uploads queued events when the app moves to the background. |
minTimeBetweenSessionsMillis | Int | 300000 | The time in the background after which the next event starts a new session. |
autocapture | AutocaptureOptions | .sessions | The events the SDK tracks automatically. |
identifyBatchIntervalMillis | Int | 30000 | Has no effect as of 1.19.4. The SDK always sends held identifies after 30 seconds. |
maxQueuedEventCount | Int | -1, no limit | The maximum number of events to keep queued. |
migrateLegacyData | Bool | true | Migrates stored data from the legacy iOS SDK. |
enableAutoCaptureRemoteConfig | Bool | true | Lets autocapture settings from Amplitude override local autocapture settings. |
AnalyticsConfig doesn't include these Configuration options: logLevel, optOut, offline, userId, deviceId, networkTrackingOptions, interactionsOptions, enableDiagnostics, and enableRequestBodyCompression. After initialization, you can set amplitude.optOut and amplitude.configuration.offline. Go to Set options that AnalyticsConfig doesn't include.
AMPAnalyticsConfig
The Objective-C Analytics options. Create it with [[AMPAnalyticsConfig alloc] init], then set its properties. Requires 0.0.2 or later.
| Property | Type | Default |
|---|---|---|
flushQueueSize | NSInteger | 30 |
flushIntervalMillis | NSInteger | 30000 |
logLevel | AMPLogLevel | AMPLogLevelWARN. Default changed in 0.0.3 |
minIDLength | NSInteger | -1, unset |
partnerID | NSString * | nil |
callback | void (^)(AMPBaseEvent *, NSInteger, NSString *) | nil |
flushMaxRetries | NSInteger | 6 |
useBatch | BOOL | NO |
serverUrl | NSString * | nil |
plan | AMPPlan * | nil |
ingestionMetadata | AMPIngestionMetadata * | nil |
trackingOptions | AMPTrackingOptions * | Every property on |
enableCoppaControl | BOOL | NO |
flushEventsOnClose | BOOL | YES |
minTimeBetweenSessionsMillis | NSInteger | 300000 |
identifyBatchIntervalMillis | NSInteger | 30000 |
autocapture | AMPAutocaptureOptions * | Sessions only |
migrateLegacyData | BOOL | YES |
enableAutoCaptureRemoteConfig | BOOL | YES |
networkTrackingOptions | AMPNetworkTrackingOptions * | The default network tracking options |
Unlike the Swift initializer, the Objective-C initializer honors logLevel. AMPAnalyticsConfig has no storage provider properties.
ExperimentPlugin.Config
The Feature Experiment options. In Objective-C, the class is ExperimentPluginConfig. Create it with [[ExperimentPluginConfig alloc] init], then set its properties. In Swift, pass the arguments in the order this table lists.
| Option | Type | Default | Description |
|---|---|---|---|
deploymentKey | String? | nil, the project API key | The Experiment client deployment key. |
debug | Bool | false | Turns on Experiment debug logging. |
fallbackVariant | Variant | Variant() | The variant variant() returns when a flag has no variant and you pass no fallback. |
initialFlags | String? | nil | Flag configurations to bootstrap local evaluation. |
initialVariants | [String: Variant] | [:] | Variants to bootstrap before the first fetch. |
source | Source | .LocalStorage | Where variant() reads variants first. |
serverUrl | String | "https://api.lab.amplitude.com" | The remote evaluation endpoint. With the default and serverZone: .EU, the plugin uses the EU host. |
flagsServerUrl | String | "https://flag.lab.amplitude.com" | The flag configuration endpoint for local evaluation. |
fetchTimeoutMillis | Int | 10000 | The fetch timeout, in milliseconds. |
retryFetchOnFailure | Bool | true | Retries a failed fetch in the background. |
automaticExposureTracking | Bool | true | Tracks $exposure when variant() returns a fetched variant. |
fetchOnStart | NSNumber? | 1 (true) | Whether start() fetches variants. |
pollOnStart | Bool | true | Whether start() polls for local evaluation flag configurations. |
flagConfigPollingIntervalMillis | Int | 300000 | The polling interval for flag configurations, in milliseconds. |
automaticFetchOnAmplitudeIdentityChange | Bool | false | Fetches again when the Analytics user ID or device ID changes. |
For details, go to the Experiment iOS SDK configuration.
SessionReplayPlugin.Config
The Session Replay options. iOS only. In Objective-C, the class is AMPSessionReplayPluginConfig. Its properties are read-only, and its only initializer takes every argument.
| Option | Type | Default | Description |
|---|---|---|---|
sampleRate | Float | 0.0, records nothing | The fraction of sessions to record, from 0 to 1. |
maskLevel | MaskLevel | .medium | How much on-screen content Session Replay masks. |
quality | QualityProfile | .high | The recording quality. |
enableRemoteConfig | Bool | true | Lets Session Replay settings from Amplitude take precedence over local values. |
webviewMappings | [String: String] | [:] | Mappings for web view content. |
autoStart | Bool | true | Starts recording at initialization. Set false and call start() to start later. |
captureWebViews | Bool | false | Records web view content. |
recordLogOptions | RecordLogOptions | .init() | How Session Replay records log messages. |
uploadConfig | UploadConfig | .init() | Upload settings, such as turning off uploads on metered networks. |
For details, go to the Session Replay iOS plugin configuration.
これは役に立ちましたか?
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.