iOS Swift SDK reference
This reference documents every public export of the AmplitudeSwift module and every Configuration option, verified against version 1.19.4. For options, go to Configuration options. To find the release that added or changed a feature, go to iOS Swift SDK release notes. For task-oriented guidance, go to Instrument and configure.
import AmplitudeSwift
The SDK has no shared instance. Create an Amplitude instance with a Configuration, keep a strong reference to it, and call every method on it. Each instance has its own identity, session, event storage, and plugins.
Methods that change state return the instance and carry the @discardableResult attribute, so calls can chain. Tracking, identify, session, and flush methods return immediately and do their work on the SDK's serial background queue. They don't return the upload result. To receive it, use callback.
Setup
init
Creates an instance. The SDK loads the stored identity, applies the configured userId and deviceId, installs its built-in plugins, and trims stored events to maxQueuedEventCount.
public init(configuration: Configuration)
| Parameter | Type | Description |
|---|---|---|
configuration | Configuration | Your API key and options. Refer to Configuration options. |
let amplitude = Amplitude(configuration: Configuration(
apiKey: "YOUR_API_KEY",
serverZone: .EU
))
Create one instance per API key and instance name. Two instances with the same API key and instanceName share storage.
Instance properties
| Property | Type | Description |
|---|---|---|
configuration | Configuration | Read-only reference to the configuration. Some of its properties can change after init. Refer to each option. |
identity | Identity | Read and write the user ID, device ID, and locally tracked user properties together. Refer to identity property. Requires 1.12.0 or later. |
sessionId | Int64 | Read-only. The current session ID, or -1 when no session is active. |
optOut | Bool | Read and write opt-out. Same as configuration.optOut. |
logger | (any Logger)? | The configured loggerProvider. |
amplitudeContext | AmplitudeContext | Context shared with other Amplitude SDKs, such as Session Replay. Most apps don't need it. |
add
Adds a plugin and calls its setup method right away. The SDK skips a plugin whose name matches one already added. Returns the instance.
@discardableResult
public func add(plugin: UniversalPlugin) -> Self
amplitude.add(plugin: AppSectionPlugin())
For the plugin contract, go to Plugin.
remove
Removes a plugin instance from every plugin type and calls its teardown().
@discardableResult
public func remove(plugin: UniversalPlugin) -> Amplitude
amplitude.remove(plugin: appSection)
plugin and plugins
Find added plugins by name or by type. Requires 1.13.0 or later.
public func plugin(name: String) -> UniversalPlugin?
public func plugins<PluginType: UniversalPlugin>(type: PluginType.Type) -> [PluginType]
let destinations = amplitude.plugins(type: AmplitudeDestinationPlugin.self)
plugin(name:) finds only plugins whose name the protocol sees. Subclasses of the base plugin classes don't expose name through the protocol. Go to Plugin.
apply
Runs a closure on every added plugin that conforms to Plugin.
public func apply(closure: (Plugin) -> Void)
flush
Uploads stored events now, and sends any held set-only identify. Skips the upload while offline is true.
@discardableResult
public func flush() -> Amplitude
amplitude.flush()
Tracking
track
Sends a custom event.
@discardableResult
public func track(eventType: String, eventProperties: [String: Any]? = nil, options: EventOptions? = nil) -> Amplitude
@discardableResult
public func track(event: BaseEvent, options: EventOptions? = nil, callback: EventCallback? = nil) -> Amplitude
| Parameter | Type | Description |
|---|---|---|
eventType | String | The event name. |
eventProperties | [String: Any]? | Optional. Event properties. |
event | BaseEvent | An event with any event fields. |
options | EventOptions? | Optional. Fields that override the instance state for this event only, such as userId, deviceId, or sessionId. |
callback | EventCallback? | Optional. Called with the upload result of this event. Refer to callback. |
amplitude.track(
eventType: "Song Played",
eventProperties: ["title": "Here Comes the Sun"],
options: EventOptions(userId: "user-12345")
)
track(eventType:eventProperties:) without options also exists, to conform to the cross-SDK AnalyticsClient protocol. It returns Void.
logEvent
Deprecated. Use track(event:).
@discardableResult
public func logEvent(event: BaseEvent) -> Amplitude
identify
Sends an $identify event that updates user properties. If options includes userId or deviceId, the SDK also changes its identity to those values. The SDK holds an identify with only $set operations and merges it with others until the next event, a flush(), an identity change, or 30 seconds.
@discardableResult
public func identify(identify: Identify, options: EventOptions? = nil) -> Amplitude
@discardableResult
public func identify(userProperties: [String: Any]?, options: EventOptions? = nil) -> Amplitude
identify(userProperties:) sends each key as a $set operation.
amplitude.identify(identify: Identify().set(property: "plan", value: "pro"))
setGroup
Assigns the current user to one group, or to several groups of one type. Sends an $identify event with groups set, which also sets the group type as a user property.
@discardableResult
public func setGroup(groupType: String, groupName: String, options: EventOptions? = nil) -> Amplitude
@discardableResult
public func setGroup(groupType: String, groupName: [String], options: EventOptions? = nil) -> Amplitude
amplitude.setGroup(groupType: "orgId", groupName: "15")
groupIdentify
Sends a $groupidentify event that updates properties of one group. groupProperties sends each key as a $set operation.
@discardableResult
public func groupIdentify(groupType: String, groupName: String, identify: Identify, options: EventOptions? = nil) -> Amplitude
@discardableResult
public func groupIdentify(groupType: String, groupName: String, groupProperties: [String: Any]?, options: EventOptions? = nil) -> Amplitude
amplitude.groupIdentify(
groupType: "orgId",
groupName: "15",
identify: Identify().set(property: "seats", value: 250)
)
revenue
Sends a revenue_amount event. revenue(revenue:) drops a Revenue without price and logs the warning Invalid revenue object, missing required fields.
@discardableResult
public func revenue(revenue: Revenue, options: EventOptions? = nil) -> Amplitude
@discardableResult
public func revenue(event: RevenueEvent) -> Amplitude
let revenue = Revenue()
revenue.price = 3.99
revenue.quantity = 3
amplitude.revenue(revenue: revenue)
logRevenue
Deprecated. Use revenue(revenue:). Has no effect as of 1.19.4: it sends nothing and returns the instance.
@discardableResult
public func logRevenue() -> Amplitude
Identity
getUserId and setUserId
Read or set the user ID for future events. setUserId(userId: nil) clears it. The SDK persists the value.
public func getUserId() -> String?
@discardableResult
public func setUserId(userId: String?) -> Amplitude
amplitude.setUserId(userId: "user-12345")
getDeviceId and setDeviceId
Read or set the device ID for future events. The SDK persists the value.
public func getDeviceId() -> String?
@discardableResult
public func setDeviceId(deviceId: String?) -> Amplitude
amplitude.setDeviceId(deviceId: UUID().uuidString)
identity property
Read or replace the user ID, device ID, and the user properties the SDK tracks locally. Setting it persists the IDs, notifies plugins, and, when userProperties change, sends an $identify that sets each key with $set. Identity has no public initializer, so change a copy. Requires 1.12.0 or later.
public var identity: Identity { get set }
var identity = amplitude.identity
identity.userId = "user-12345"
identity.userProperties["plan"] = "pro"
amplitude.identity = identity
userProperties reflects only $set, $unset, and $clearAll operations sent from this instance since launch. It doesn't read user properties from Amplitude.
reset
Clears the user ID and the locally tracked user properties, chooses a device ID again, and calls onReset() on plugins. With IDFV tracking on, the new device ID is the same IDFV. It doesn't start a new session or send an event.
@discardableResult
public func reset() -> Amplitude
amplitude.reset()
Sessions
getSessionId and setSessionId
Read the current session ID, or end the current session and start one with the given ID, in milliseconds since the Unix epoch. A negative timestamp ends the current session without starting one. With session autocapture on, the SDK sends session_end and session_start, unless opt-out is on.
public func getSessionId() -> Int64
@discardableResult
public func setSessionId(timestamp: Int64) -> Amplitude
@discardableResult
public func setSessionId(date: Date) -> Amplitude
amplitude.setSessionId(date: Date())
Privacy
optOut
Read or set opt-out. While true, the SDK drops every new event and logs Skip event based on opt out configuration. Events stored earlier still upload. The SDK doesn't persist the value.
public var optOut: Bool { get set }
amplitude.optOut = true
BaseEvent and EventOptions
BaseEvent is the event class. EventOptions is its superclass and holds every field except the event name and the four property dictionaries. Both are open classes. Every initializer parameter is optional except eventType, and Swift requires them in declaration order: the EventOptions fields first, then eventType, eventProperties, userProperties, groups, and groupProperties.
let event = BaseEvent(
insertId: "song-played-8f2c",
eventType: "Song Played",
eventProperties: ["title": "Here Comes the Sun"],
groups: ["orgId": "15"]
)
| Field | Type | Wire key | Description |
|---|---|---|---|
eventType | String | event_type | BaseEvent only. Required. |
eventProperties, userProperties, groups, groupProperties | [String: Any]? | event_properties, user_properties, groups, group_properties | BaseEvent only. |
userId, deviceId | String? | user_id, device_id | Set from the instance when nil. An event needs at least one, or the SDK drops it. |
timestamp | Int64? | time | Milliseconds since the Unix epoch. Set to the current time when nil. |
sessionId | Int64? | session_id | Set from the current session when nil. -1 marks an out-of-session event. |
eventId | Int64? | event_id | Set by the SDK to an increasing counter. |
insertId | String? | insert_id | Deduplication key. Set to a UUID when nil. |
locationLat, locationLng | Double? | location_lat, location_lng | Not set by the SDK. |
appVersion | String? | app_version | Not set by the SDK. |
versionName, platform, osName, osVersion, deviceManufacturer, deviceModel, carrier, language, idfv | String? | snake case of the name | Set by the SDK unless turned off in trackingOptions. |
deviceBrand, region, city, dma, idfa, adid | String? | snake case of the name | Not set by the SDK. |
country | String? | country | Set from the device locale only when IP tracking is off. |
ip | String? | ip | "$remote" by default, so Amplitude uses the request IP. |
library | String? | library | amplitude-swift/<version>. |
partnerId | String? | partner_id | Set from the partnerId option when nil. |
plan, ingestionMetadata | Plan?, IngestionMetadata? | plan, ingestion_metadata | Set from the configuration when nil. Refer to Types. |
revenue, price, quantity, productId, revenueType, currency | Double?, Int?, String? | snake case of the name | Top-level revenue fields of the HTTP V2 API. Revenue uses event properties instead. |
extra | [String: Any]? | Not sent | Data for plugins. The SDK never uploads it. |
callback | EventCallback? | Not sent | Per-event result callback. |
mergeEventOptions(eventOptions:) copies every non-nil field of the argument onto the receiver.
Predefined events
| Class | eventType | Public initializers | Properties |
|---|---|---|---|
ScreenViewedEvent | [Amplitude] Screen Viewed | init(screenName: String) | [Amplitude] Screen Name |
DeepLinkOpenedEvent | [Amplitude] Deep Link Opened | init(url: URL), init(url: NSURL), init(activity: NSUserActivity), init(url: String?, referrer: String? = nil) | [Amplitude] Link URL, [Amplitude] Link Referrer. init(activity:) reads webpageURL and referrerURL. |
ElementInteractionEvent | [Amplitude] Element Interacted | None. The SDK creates it. | Refer to Element interactions. |
NetworkRequestEvent | [Amplitude] Network Request | None. The SDK creates it. | Refer to Network requests. |
IdentifyEvent | $identify | None | user_properties |
GroupIdentifyEvent | $groupidentify | None | groups, group_properties |
RevenueEvent | revenue_amount | None | Refer to Revenue class. |
Autocapture also sends plain BaseEvent events: session_start, session_end, [Amplitude] Application Installed, [Amplitude] Application Updated, [Amplitude] Application Opened, [Amplitude] Application Backgrounded, [Amplitude] Rage Click, and [Amplitude] Dead Click.
Identify class
Identify builds user property or group property operations for identify(identify:) and groupIdentify(groupType:groupName:identify:). Each method returns the same object, so calls chain. Each property can take only one operation per object. The SDK ignores later operations on the same property and every operation after clearAll(), and logs a warning.
let identify = Identify()
| Method | Operation | Value types | Description |
|---|---|---|---|
set(property:value:) | $set | Bool, Int, Int64, Float, Double, String, [String: Any], [Any], arrays of Bool, Int, Int64, Float, Double, String, or Any? | Sets the value. |
setOnce(property:value:) | $setOnce | Same as set | Sets the value if the property has none. |
append(property:value:) | $append | Same as set | Appends to a list. |
prepend(property:value:) | $prepend | Same as set | Prepends to a list. |
postInsert(property:value:) | $postInsert | Same as set | Appends values not already in the list. |
preInsert(property:value:) | $preInsert | Same as set | Prepends values not already in the list. |
remove(property:value:) | $remove | Same as set | Removes values from a list. |
add(property:value:) | $add | Int, Int64, Float, Double | Adds to a numeric value. |
unset(property:) | $unset | None | Removes the property. |
clearAll() | $clearAll | None | Removes every property. You can't undo it. |
The SDK ignores an operation with an empty property name or a nil value, and logs a warning. These warnings come from an internal logger at the .warn level, not from your loggerProvider.
Revenue class
Revenue builds the properties of a revenue_amount event. Set its properties, then pass it to revenue(revenue:).
let revenue = Revenue()
| Member | Type | Event property | Default | Description |
|---|---|---|---|---|
productId | String? | $productId | nil | Product identifier, such as the App Store product ID. Ignores nil and empty strings. |
price | Double? | $price | nil | Price of one item. Required. Can be negative. |
quantity | Int | $quantity | 1 | Number of items. Ignores values of 0 or less. |
revenue | Double? | $revenue | nil | Total revenue. When unset, Amplitude computes price * quantity. |
revenueType | String? | $revenueType | nil | Category, such as subscription or refund. Required for revenue verification. |
currency | String? | $currency | nil | ISO 4217 currency code for conversion. Requires 1.11.6 or later. |
receipt | String? | $receipt | nil | Purchase receipt. |
receiptSig | String? | $receiptSig | nil | Receipt signature. Required for revenue verification. |
properties | [String: Any]? | Merged | nil | Extra event properties. The revenue properties above win on conflict. |
setReceipt(receipt:receiptSignature:) | Method | Not applicable | Not applicable | Sets receipt and receiptSig. Returns the object. |
Plugin
A plugin runs code for each event, or reacts to SDK state changes. Pass it to add(plugin:). For how the SDK orders plugins, go to How plugins run.
Plugin protocol
| Member | Required | Description |
|---|---|---|
type: PluginType | Yes | .before, .enrichment, .destination, .utility, or .observe. Only before, enrichment, and destination plugins receive events. |
name: String? | No | Unique name. The SDK skips a plugin whose name matches one already added. Default nil. |
setup(amplitude:) | No | Runs once, when you call add(plugin:). |
execute(event:) -> BaseEvent? | No | Returns the event, possibly changed, or nil to drop it for later plugins. Default returns the event. |
teardown() | No | Runs on remove(plugin:). |
onUserIdChanged(_:) | No | Runs when the user ID changes. |
onDeviceIdChanged(_:) | No | Runs when the device ID changes. |
onSessionIdChanged(_:) | No | Runs when a session starts or ends. Requires 1.9.0 or later. |
onOptOutChanged(_:) | No | Runs when optOut changes. Requires 1.9.0 or later. |
onReset() | No | Runs on reset(). Requires 1.15.3 or later. |
onIdentityChanged(_:) | No | Runs when the identity changes, with an AnalyticsIdentity. |
Plugin extends UniversalPlugin from AmplitudeCore, the protocol other Amplitude SDKs share. A plugin that conforms only to UniversalPlugin runs as an enrichment plugin and receives setup(analyticsClient:amplitudeContext:) and execute(_:) instead. Requires 1.13.0 or later.
EventPlugin extends Plugin with track(event:), identify(event:), groupIdentify(event:), revenue(event:), and flush().
Base classes
| Class | Type | Notes |
|---|---|---|
BasePlugin | None | Stores a weak amplitude reference in setup(amplitude:). Declares execute(event:) and the four on...Changed hooks as overridable. teardown() is public but not overridable. |
BeforePlugin | .before | Subclass of BasePlugin. |
EnrichmentPlugin | .enrichment | Subclass of BasePlugin. |
DestinationPlugin | .destination | Subclass of BasePlugin that conforms to EventPlugin. Its execute(event:) calls identify(event:) for $identify, revenue(event:) for revenue_amount, and track(event:) for every other event, including $groupidentify. Override those methods, not execute(event:). |
ObservePlugin | .observe | Subclass of BasePlugin. Never receives events. |
UtilityPlugin | .utility | Subclass of BasePlugin. Never receives events. |
BasePlugin doesn't declare name, onReset(), or onIdentityChanged(_:). A subclass that adds them doesn't override the protocol's defaults, so the SDK doesn't see the name or call the hooks. To use them, conform your own class to Plugin.
final class ResetAwarePlugin: Plugin {
let type: PluginType = .enrichment
let name: String? = "reset-aware"
func execute(event: BaseEvent) -> BaseEvent? { event }
func onReset() {
// Clear state tied to the signed-out user.
}
}
Built-in plugins
| Class | Description |
|---|---|
AmplitudeDestinationPlugin | The destination that stores events, holds set-only identifies, and uploads to Amplitude. |
NetworkConnectivityCheckerPlugin | Watches connectivity with NWPathMonitor and sets configuration.offline. Not installed when offline is nil or on watchOS. NetworkConnectivityCheckerPlugin.Disabled is nil, the value for the offline option that turns it off. |
Types
| Type | Declaration | Description |
|---|---|---|
Identity | struct with userId: String?, deviceId: String?, userProperties: [String: Any] | The value of identity. No public initializer. |
Plan | struct with branch, source, version, versionId, all String? | Tracking plan metadata. init(branch:source:version:versionId:), all default nil. |
IngestionMetadata | struct with sourceName, sourceVersion, both String? | Ingestion source metadata, sent as source_name and source_version. |
ServerZone | enum ServerZone: Int { case US, EU } | Data region. Defined in AmplitudeCore. |
LogLevel, LogLevelEnum | enum LogLevel: Int { case off, error, warn, log, debug } | Values 0 to 4. LogLevelEnum is a type alias. The lowercase cases require 1.17.0 or later. The uppercase aliases, such as LogLevelEnum.DEBUG, are deprecated. |
Logger | protocol Logger: CoreLogger { var logLevel: Int { get set } } | Requires error(message:), warn(message:), log(message:), debug(message:), and an associated LogLevel type. |
ConsoleLogger | class ConsoleLogger: Logger | The default logger. Writes to os_log with subsystem Amplitude and category Logging. init(logLevel: Int = LogLevelEnum.off.rawValue). |
EventCallback | typealias EventCallback = (BaseEvent, Int, String) -> Void | Receives the event, a status code, and a message. Refer to callback. |
PluginType | enum PluginType: Int { case before, enrichment, destination, utility, observe } | Plugin type. |
UIView.amp_ignoreInteractionEvent | func amp_ignoreInteractionEvent(rageClick: Bool = true, deadClick: Bool = true) | Excludes the view and its subviews from rage click and dead click detection. UIKit only. In Objective-C: amp_ignoreInteractionEventWithRageClick:deadClick:. Requires 1.14.0 or later. |
Storage
Implement Storage to replace the SDK's storage with storageProvider or identifyStorageProvider. The built-in implementation isn't public, so your type implements every member.
public protocol Storage {
func write(key: StorageKey, value: Any?) throws
func read<T>(key: StorageKey) -> T?
func getEventsString(eventBlock: URL) -> String?
func remove(eventBlock: URL)
func splitBlock(eventBlock: URL, events: [BaseEvent])
func rollover()
func reset()
func getResponseHandler(
configuration: Configuration,
eventPipeline: EventPipeline,
eventBlock: URL,
eventsString: String
) -> ResponseHandler
}
write(key: .EVENTS, value:)receives eachBaseEventto store.read(key: .EVENTS)returns the stored files as[URL], oldest first. Other keys store single values.rollover()closes the current file. The SDK calls it at the start of every upload.splitBlock(eventBlock:events:)replaces one file with two halves after a413response.getResponseHandler(...)returns aResponseHandlerwhosehandle(result:) -> Boolprocesses the upload result. Returntruewhen you've handled the result and the next file can upload right away. Returnfalseto count a failure and back off.
StorageKey cases: LAST_EVENT_ID, PREVIOUS_SESSION_ID, LAST_EVENT_TIME, OPT_OUT, EVENTS, USER_ID, DEVICE_ID, APP_BUILD, APP_VERSION, and STORAGE_VERSION. The SDK doesn't read or write OPT_OUT. PersistentStorageVersion describes the storage layout version for migrations.
Integration exports
These exports exist for other Amplitude SDKs and for the SDK's own tests. Most apps don't need them.
| Export | Purpose |
|---|---|
Timeline, EventPipeline, IdentifyInterceptor, Sessions | The SDK's internal pipeline. The instance doesn't expose them. |
DefaultEventUtils | Builds the app lifecycle events. |
Diagnostics, SandboxHelper, NetworkPath, NetworkTaskListener | Diagnostics, sandbox detection, and network observation helpers. |
Atomic<T> | Deprecated. A thread-safe wrapper. |
Constants | DEFAULT_API_HOST, EU_DEFAULT_API_HOST, MIN_IDENTIFY_BATCH_INTERVAL_MILLIS, Constants.Configuration defaults, and Constants.Storage.STORAGE_PREFIX. |
Configuration.Defaults | The default value of every configuration option, such as Configuration.Defaults.flushQueueSize. Requires 1.12.0 or later. |
Objective-C names
The Objective-C interface wraps the Swift classes. Import AmplitudeSwift, plus AmplitudeCore for AMPServerZone.
| Swift | Objective-C | Members |
|---|---|---|
Amplitude | Amplitude | +initWithConfiguration:, configuration, storage, track:, track:callback:, track:options:, track:options:callback:, track:eventProperties:, track:eventProperties:options:, identify:, identify:options:, groupIdentify:groupName:identify:, groupIdentify:groupName:identify:options:, setGroup:groupName:, setGroup:groupName:options:, setGroup:groupNames:, setGroup:groupNames:options:, revenue:, revenue:options:, add:, remove:, flush, setUserId:, setDeviceId:, getUserId, getDeviceId, getSessionId, setSessionIdWithTimestamp:, setSessionIdWithDate:, reset |
Configuration | AMPConfiguration | +initWithApiKey: and +initWithApiKey:instanceName: (also as alloc initializers), -initWithApiKey:instanceName:enableAutocaptureRemoteConfig: (alloc initializer only), and a property for each option except storageProvider, identifyStorageProvider, maxQueuedEventCount, and enableDiagnostics. apiKey, instanceName, and enableAutoCaptureRemoteConfig are read-only. minIdLength uses -1 for unset, and offline is an NSNumber. |
BaseEvent | AMPBaseEvent | +initWithEventType:, +initWithEventType:eventProperties:, eventType, and eventProperties, userProperties, groups, groupProperties as AMPProperties |
EventOptions | AMPEventOptions | A property for each field, mergeEventOptions: |
Identify | AMPIdentify | set:value:, setOnce:value:, prepend:value:, append:value:, postInsert:value:, preInsert:value:, remove:value:, add:valueInt:, add:valueInt64:, add:valueDouble:, add:valueFloat:, unset:, clearAll |
Revenue | AMPRevenue | productId, quantity, price (NaN for unset), revenue, revenueType, currency, receipt, receiptSig, properties, setReceipt:receiptSignature: |
Plan, IngestionMetadata | AMPPlan, AMPIngestionMetadata | The same properties |
TrackingOptions | AMPTrackingOptions | Each disableTrack... and shouldTrack... method |
AutocaptureOptions | AMPAutocaptureOptions | sessions, appLifecycles, screenViews, elementInteractions, networkTracking, frustrationInteractions, all, default, initWithOptionsToUnion:, and set operations |
InteractionsOptions | AMPInteractionsOptions, AMPRageClickOptions, AMPDeadClickOptions | rageClick, deadClick, enabled |
NetworkTrackingOptions | AMPNetworkTrackingOptions, AMPNetworkTrackingCaptureRule | initWithCaptureRules:ignoreHosts:ignoreAmplitudeRequests:, defaultOptions. Rules: initWithHosts:statusCodeRange: only. |
DefaultTrackingOptions | AMPDefaultTrackingOptions | Deprecated. Use AMPAutocaptureOptions. |
Plugin | AMPPlugin | +initWithType:execute:, +initWithType:setup:execute:, +initWithType:execute:flush:, +initWithType:setup:execute:flush: |
DeepLinkOpenedEvent | AMPDeepLinkOpenedEvent | +initWithUrl:, +initWithUrl:referrer:, +initWithActivity:. The misspelled initWihUrl: selectors also exist. |
ScreenViewedEvent | AMPScreenViewedEvent | +initWithScreenName: |
| Property dictionaries | AMPProperties | get:, set:value:, remove: |
| Storage | AMPStorage | getEventsStrings, getInterceptedIdentifiesStrings |
NetworkConnectivityCheckerPlugin | AMPNetworkConnectivityCheckerPlugin | Disabled (nil) |
| Enums | AMPLogLevel, AMPPluginType, AMPServerZone, AMPCoreLogLevel | AMPLogLevelOFF through AMPLogLevelDEBUG, AMPPluginTypeBefore through AMPPluginTypeObserve, AMPServerZoneUS, AMPServerZoneEU |
optOut on the Objective-C Amplitude class isn't public. Set amplitude.configuration.optOut. The loggerProvider block is (NSInteger logLevel, NSString *message), and logLevel is the configured level, not the level of the message.
Configuration options
This section lists every option of Configuration, as of 1.19.4. Every option except apiKey is optional. Swift requires labeled arguments in declaration order, so pass the options you use in this order:
apiKey, flushQueueSize, flushIntervalMillis, instanceName, optOut, storageProvider, identifyStorageProvider, logLevel, loggerProvider, minIdLength, partnerId, callback, flushMaxRetries, useBatch, serverZone, serverUrl, plan, ingestionMetadata, trackingOptions, enableCoppaControl, flushEventsOnClose, minTimeBetweenSessionsMillis, autocapture, identifyBatchIntervalMillis, maxQueuedEventCount, migrateLegacyData, offline, networkTrackingOptions, enableAutoCaptureRemoteConfig, interactionsOptions, enableDiagnostics, enableRequestBodyCompression, userId, deviceId.
let amplitude = Amplitude(configuration: Configuration(
apiKey: "YOUR_API_KEY",
flushQueueSize: 50,
logLevel: .log,
serverZone: .EU,
autocapture: [.sessions, .appLifecycles]
))
Options marked "Set at init" are read-only, or read only when you create the Amplitude instance, so changing them afterward has no effect. Configuration.Defaults holds each default value.
Identity and session
| Option | Type | Default | Description |
|---|---|---|---|
apiKey | String | Required | Your Amplitude project API key. Sent as api_key in each upload. The SDK doesn't validate it. Set at init. |
instanceName | String | "$default_instance" | Scopes storage and identity. An empty string becomes the default. Give each instance a distinct name. Set at init. |
userId | String? | nil | User ID applied before the first event, replacing the stored value. nil keeps the stored value. Set at init. Requires 1.19.0 or later. |
deviceId | String? | nil | Device ID applied before the first event, replacing the stored value. nil keeps the stored value or chooses one. Set at init. Requires 1.19.0 or later. |
minTimeBetweenSessionsMillis | Int | 300000 (5 minutes) | Time in the background, or between background events, after which the next event starts a new session. Foreground sessions don't time out. |
optOut | Bool | false | When true, the SDK drops every new event. Not persisted. Notifies plugins on change. |
minIdLength | Int? | nil (Amplitude enforces 5) | Minimum accepted length for user_id and device_id. Sent as options.min_id_length with each upload. |
Data collection
| Option | Type | Default | Description |
|---|---|---|---|
autocapture | AutocaptureOptions | .sessions | Events the SDK tracks automatically. Refer to AutocaptureOptions. Set at init. Requires 1.8.0 or later. |
defaultTracking | DefaultTrackingOptions | sessions: true | Deprecated. Use autocapture. Property only, not an initializer parameter of the main initializer. Setting it overwrites autocapture with its sessions, app lifecycles, and screen views values. |
trackingOptions | TrackingOptions | A shared TrackingOptions() with every field on | Device and app fields the SDK adds to events. Refer to TrackingOptions. Pass a new object rather than changing the shared default. |
enableCoppaControl | Bool | false | Turns off IDFV, IP address, city, and IDFA tracking on trackingOptions with each event. The device ID chosen at launch can still be the IDFV unless you also call disableTrackIDFV(). |
partnerId | String? | nil | Sets partner_id on events that have none. For partners who build event ingestion integrations. |
plan | Plan? | nil | Tracking plan metadata attached to events that have none. Set by Ampli. |
ingestionMetadata | IngestionMetadata? | nil | Ingestion source metadata attached to events that have none. Set by Ampli and integrations. |
migrateLegacyData | Bool | true | On first launch, moves events, user ID, and device ID from the maintenance iOS SDK. Runs only in sandboxed apps. Set at init. |
TrackingOptions
TrackingOptions() turns on every field. Each disableTrack...() method returns the object, and each has a matching shouldTrack...() -> Bool.
| Method | Field | Description |
|---|---|---|
disableTrackVersionName() | version_name | The app's CFBundleShortVersionString. |
disableTrackOsName() | os_name | For example ios, ipados, macos, or watchos. |
disableTrackOsVersion() | os_version | The OS version. |
disableTrackDeviceManufacturer() | device_manufacturer | Apple. |
disableTrackDeviceModel() | device_model | The hardware model identifier. |
disableTrackCarrier() | carrier | The SIM carrier on iOS devices, otherwise Unknown. |
disableTrackIpAddress() | ip | "$remote", so Amplitude derives location from the request IP. |
disableTrackCountry() | country | Sent from the device locale only when IP tracking is off. |
disableTrackIDFV() | idfv | Also stops the SDK from using the IDFV as the device ID. Requires 1.4.0 or later for the device ID behavior. |
disableTrackLanguage() | language | The first preferred language. |
disableTrackPlatform() | platform | iOS, tvOS, visionOS, macOS, or watchOS. |
disableTrackCity() | city | Has no effect as of 1.19.4. The SDK never sends city. |
disableTrackDMA() | dma | Has no effect as of 1.19.4. The SDK never sends dma. |
disableTrackRegion() | region | Has no effect as of 1.19.4. The SDK never sends region. |
There's no method for IDFA or for latitude and longitude, because the SDK doesn't collect them.
DefaultTrackingOptions
Deprecated. Use AutocaptureOptions. DefaultTrackingOptions(sessions: Bool = true, appLifecycles: Bool = false, screenViews: Bool = false), with the presets DefaultTrackingOptions.ALL and DefaultTrackingOptions.NONE. A deprecated Configuration convenience initializer takes defaultTracking: in place of autocapture:, and lacks the options added after it.
Delivery
| Option | Type | Default | Description |
|---|---|---|---|
serverZone | ServerZone | .US | Data center for uploads, remote configuration, and diagnostics. Remote configuration and diagnostics read it at init. |
serverUrl | String? | nil, derived from serverZone and useBatch | Upload endpoint. A non-empty value overrides serverZone and useBatch for events. |
useBatch | Bool | false | Sends to the Batch Event Upload API (/batch) instead of HTTP V2 (/2/httpapi). |
flushQueueSize | Int | 30 | Events tracked since the last upload that trigger an upload. 0 acts as 1. Doesn't cap request size. |
flushIntervalMillis | Int | 30000 | Interval of the repeating upload timer. Set at init. |
flushMaxRetries | Int | 6 | Consecutive failed uploads after which the SDK sets offline to true and stops uploading. Default changed in 1.11.9. |
flushEventsOnClose | Bool | true | Uploads when the app moves to the background (on macOS, when it resigns active). |
enableRequestBodyCompression | Bool | false | Gzip-compresses bodies sent to a custom serverUrl. Amplitude's own endpoints always use compression. Requires 1.17.3 or later. |
offline | Bool? | false | true stops uploads and keeps events stored. Managed by the connectivity monitor and by failed retries. nil (NetworkConnectivityCheckerPlugin.Disabled) turns off the monitor. Requires 1.3.0 or later. |
maxQueuedEventCount | Int | -1 (no limit) | At init, deletes the oldest storage files until the newest files hold at least this many events. Deletes whole files only, so more events can remain. Set at init. Requires 1.9.1 or later. |
storageProvider | (any Storage)? | nil, file and UserDefaults storage | Storage for events and identity. Refer to Storage. Not available in Objective-C. Set at init. |
identifyStorageProvider | (any Storage)? | nil, file storage | Storage for held set-only identify events. Not available in Objective-C. Set at init. |
identifyBatchIntervalMillis | Int | 30000 | Has no effect as of 1.19.4. The SDK always sends held identifies after 30 seconds. |
callback | EventCallback? | nil | Called with the upload result of every event. Refer to callback. |
callback
callback receives the result of every event after Amplitude accepts or rejects it. A per-event closure passed to track(event:options:callback:), or set as EventOptions.callback, fires too.
public typealias EventCallback = (BaseEvent, Int, String) -> Void
let amplitude = Amplitude(configuration: Configuration(
apiKey: "YOUR_API_KEY",
callback: { event, code, message in
if code != 200 {
print("Amplitude rejected \(event.eventType): \(code) \(message)")
}
}
))
| Result | code | message |
|---|---|---|
| Uploaded | The HTTP status, 200 | Successfully send event |
| Invalid API key, every event in the request | 400 | Invalid API key: <key> |
| Event Amplitude rejected as invalid or silenced | 400 | The server's error text, or empty |
| Single event too large | 413 | The server's error text, or empty |
The callback doesn't fire for 429, 408, 5xx, or connection errors, because the SDK keeps those events and retries. It also doesn't fire for events dropped by opt-out, by a plugin, or for missing both userId and deviceId. Per-event closures live in memory, so the SDK loses them if the app quits before the upload. The SDK calls them on its background queue.
Logging, remote configuration, and diagnostics
| Option | Type | Default | Description |
|---|---|---|---|
logLevel | LogLevelEnum | .warn | .off, .error, .warn, .log, or .debug. Copied to loggerProvider.logLevel at init. Set at init. |
loggerProvider | any Logger | ConsoleLogger() | Receives every SDK log message. Filter on logLevel in your implementation. |
enableAutoCaptureRemoteConfig | Bool | true | Applies your project's remote Autocapture settings on top of autocapture, interactionsOptions, and networkTrackingOptions. Read-only. Requires 1.13.0 or later. |
enableDiagnostics | Bool | true | Lets the SDK report its own errors and upload health to Amplitude. Requires 1.16.0 or later. |
Autocapture options
For behavior and examples, go to Autocapture.
| Option | Type | Default | Description |
|---|---|---|---|
interactionsOptions | InteractionsOptions | InteractionsOptions(), rage and dead clicks on | Which frustration interactions to detect with .frustrationInteractions. Set at init. Requires 1.14.0 or later. |
networkTrackingOptions | NetworkTrackingOptions | NetworkTrackingOptions.default | Which requests to capture with .networkTracking. Set at init. Requires 1.12.0 or later. |
AutocaptureOptions
An OptionSet with rawValue: Int.
| Member | Description |
|---|---|
.sessions | session_start and session_end events. |
.appLifecycles | Application installed, updated, opened, and backgrounded events. UIKit platforms only. |
.screenViews | [Amplitude] Screen Viewed for UIKit view controllers. |
.elementInteractions | [Amplitude] Element Interacted for UIKit controls and gesture recognizers. |
.networkTracking | [Amplitude] Network Request. Not on watchOS. Requires 1.12.0 or later. |
.frustrationInteractions | [Amplitude] Rage Click and [Amplitude] Dead Click. UIKit platforms only. Requires 1.14.0 or later. |
.all | Every member above. |
There's no deep link option. Track DeepLinkOpenedEvent yourself.
InteractionsOptions
| Key | Type | Default | Description |
|---|---|---|---|
rageClick | RageClickOptions | RageClickOptions() | RageClickOptions(enabled: Bool = true). Four taps within one second and 50 points. |
deadClick | DeadClickOptions | DeadClickOptions() | DeadClickOptions(enabled: Bool = true). A tap with no UI change within three seconds. Requires a plugin that reports interface changes, such as Session Replay. |
NetworkTrackingOptions
NetworkTrackingOptions(captureRules: [CaptureRule], ignoreHosts: [String] = [], ignoreAmplitudeRequests: Bool = true)
| Key | Type | Default | Description |
|---|---|---|---|
captureRules | [CaptureRule] | Required. .default has one rule: hosts: ["*"], statusCodeRange: "500-599" | Rules. The last rule that matches the request decides, with its own statusCodeRange. |
ignoreHosts | [String] | [] | Hosts never captured, checked before rules. Supports * wildcards. |
ignoreAmplitudeRequests | Bool | true | Adds *.amplitude.com to ignoreHosts. |
An invalid rule, such as a malformed statusCodeRange, turns off network tracking and logs NetworkTrackingPlugin: Failed to parse options.
CaptureRule
NetworkTrackingOptions.CaptureRule has two initializers:
init(hosts: [String], statusCodeRange: String = "500-599")
init(urls: [URLPattern], methods: [String] = ["*"], statusCodeRange: String = "500-599",
requestHeaders: CaptureHeader? = nil, responseHeaders: CaptureHeader? = nil,
requestBody: CaptureBody? = nil, responseBody: CaptureBody? = nil)
| Key | Type | Default | Description |
|---|---|---|---|
hosts | [String] | None | Hosts to match. Supports *, ignores case. Ignored when urls is set. |
urls | [URLPattern] | None | .exact(String) or .regex(String), matched against the full URL including query and fragment. Requires 1.15.0 or later. |
methods | [String] | ["*"] | HTTP methods to match. Requires 1.15.0 or later. |
statusCodeRange | String | "500-599" | Comma-separated codes and ranges, such as "0,400-499". 0 means the request failed without a response. |
requestHeaders, responseHeaders | CaptureHeader? | nil | Headers to capture. Requires 1.15.0 or later. |
requestBody, responseBody | CaptureBody? | nil | JSON body paths to capture. Requires 1.15.0 or later. |
CaptureHeader
CaptureHeader(allowlist: [String] = [], captureSafeHeaders: Bool = true)
| Key | Type | Default | Description |
|---|---|---|---|
allowlist | [String] | [] | Header names to capture, ignoring case. The SDK never captures authorization, cookie, or proxy-authorization. |
captureSafeHeaders | Bool | true | Also captures a fixed list of non-sensitive headers, such as content-type, cache-control, etag, retry-after, and x-frame-options. |
CaptureBody
CaptureBody(allowlist: [String], excludelist: [String] = [])
| Key | Type | Default | Description |
|---|---|---|---|
allowlist | [String] | Required | JSON paths to capture, case-sensitive. * matches one level and ** matches any number of levels. |
excludelist | [String] | [] | Paths to remove from what allowlist selected. Requires 1.15.2 or later. |
CaptureBody(allowlist:blocklist:) is deprecated. Use excludelist.
Was this helpful?
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.