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.

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

swift
public init(configuration: Configuration)
swift
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

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.

swift
@discardableResult
public func add(plugin: UniversalPlugin) -> Self
swift
amplitude.add(plugin: AppSectionPlugin())

For the plugin contract, go to Plugin.

remove

Removes a plugin instance from every plugin type and calls its teardown().

swift
@discardableResult
public func remove(plugin: UniversalPlugin) -> Amplitude
swift
amplitude.remove(plugin: appSection)

plugin and plugins

Find added plugins by name or by type. Requires 1.13.0 or later.

swift
public func plugin(name: String) -> UniversalPlugin?
public func plugins<PluginType: UniversalPlugin>(type: PluginType.Type) -> [PluginType]
swift
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.

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

swift
@discardableResult
public func flush() -> Amplitude
swift
amplitude.flush()

Tracking

track

Sends a custom event.

swift
@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
swift
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:).

swift
@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.

swift
@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.

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

swift
@discardableResult
public func setGroup(groupType: String, groupName: String, options: EventOptions? = nil) -> Amplitude

@discardableResult
public func setGroup(groupType: String, groupName: [String], options: EventOptions? = nil) -> Amplitude
swift
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.

swift
@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
swift
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.

swift
@discardableResult
public func revenue(revenue: Revenue, options: EventOptions? = nil) -> Amplitude

@discardableResult
public func revenue(event: RevenueEvent) -> Amplitude
swift
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.

swift
@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.

swift
public func getUserId() -> String?

@discardableResult
public func setUserId(userId: String?) -> Amplitude
swift
amplitude.setUserId(userId: "user-12345")

getDeviceId and setDeviceId

Read or set the device ID for future events. The SDK persists the value.

swift
public func getDeviceId() -> String?

@discardableResult
public func setDeviceId(deviceId: String?) -> Amplitude
swift
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.

swift
public var identity: Identity { get set }
swift
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.

swift
@discardableResult
public func reset() -> Amplitude
swift
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.

swift
public func getSessionId() -> Int64

@discardableResult
public func setSessionId(timestamp: Int64) -> Amplitude

@discardableResult
public func setSessionId(date: Date) -> Amplitude
swift
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.

swift
public var optOut: Bool { get set }
swift
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.

swift
let event = BaseEvent(
    insertId: "song-played-8f2c",
    eventType: "Song Played",
    eventProperties: ["title": "Here Comes the Sun"],
    groups: ["orgId": "15"]
)

mergeEventOptions(eventOptions:) copies every non-nil field of the argument onto the receiver.

Predefined events

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.

swift
let identify = Identify()

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:).

swift
let revenue = Revenue()

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

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

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.

swift
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

Types

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.

swift
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 each BaseEvent to 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 a 413 response.
  • getResponseHandler(...) returns a ResponseHandler whose handle(result:) -> Bool processes the upload result. Return true when you've handled the result and the next file can upload right away. Return false to 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.

Objective-C names

The Objective-C interface wraps the Swift classes. Import AmplitudeSwift, plus AmplitudeCore for AMPServerZone.

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.

swift
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

Data collection

TrackingOptions

TrackingOptions() turns on every field. Each disableTrack...() method returns the object, and each has a matching shouldTrack...() -> Bool.

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

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.

swift
public typealias EventCallback = (BaseEvent, Int, String) -> Void
swift
let amplitude = Amplitude(configuration: Configuration(
    apiKey: "YOUR_API_KEY",
    callback: { event, code, message in
        if code != 200 {
            print("Amplitude rejected \(event.eventType): \(code) \(message)")
        }
    }
))

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

Autocapture options

For behavior and examples, go to Autocapture.

AutocaptureOptions

An OptionSet with rawValue: Int.

There's no deep link option. Track DeepLinkOpenedEvent yourself.

InteractionsOptions

NetworkTrackingOptions

NetworkTrackingOptions(captureRules: [CaptureRule], ignoreHosts: [String] = [], ignoreAmplitudeRequests: Bool = true)

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:

swift
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)

CaptureHeader

CaptureHeader(allowlist: [String] = [], captureSafeHeaders: Bool = true)

CaptureBody

CaptureBody(allowlist: [String], excludelist: [String] = [])

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.

On this page