This is the official documentation for the Amplitude Analytics iOS SDK.
Add the dependency to your Podfile
:
1pod 'AmplitudeSwift', '~> 1.0.0'
Run pod install
in the project directory.
Navigate to File
> Swift Package Manager
> Add Package Dependency
. This opens a dialog that allows you to add a package dependency.
Enter the URL https://github.com/amplitude/Amplitude-Swift
in the search bar.
Xcode will automatically resolve to the latest version. Or you can select a specific version.
Click the "Next" button to confirm the addition of the package as a dependency.
Build your project to make sure the package is properly integrated.
Cartfile
.
1github "amplitude/Amplitude-Swift" ~> 1.0.0
Check out the Carthage docs for more info.
You must initialize the SDK before you can instrument. The API key for your Amplitude project is required.
1let amplitude = Amplitude(configuration: Configuration(2 apiKey: AMPLITUDE_API_KEY3))
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];2Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Configuration options
Name
Description
Default Value
apiKey
The apiKey of your project.
nil
instanceName
The name of the instance. Instances with the same name will share storage and identity. For isolated storage and identity use a unique
instanceName
for each instance."default_instance"
storageProvider
Implements a custom
storageProvider
class from Storage
. Not supported in Objective-C.PersistentStorage
logLevel
The log level enums:
LogLevelEnum.OFF
, LogLevelEnum.ERROR
, LogLevelEnum.WARN
, LogLevelEnum.LOG
, LogLevelEnum.DEBUG
LogLevelEnum.WARN
loggerProvider
Implements a custom
loggerProvider
class from the Logger, and pass it in the configuration during the initialization to help with collecting any error messages from the SDK in a production environment.ConsoleLogger
flushIntervalMillis
The amount of time SDK will attempt to upload the unsent events to the server or reach
flushQueueSize
threshold.30000
flushQueueSize
SDK will attempt to upload once unsent event count exceeds the event upload threshold or reach
flushIntervalMillis
interval.30
flushMaxRetries
Maximum retry times.
5
minIdLength
The minimum length for user id or device id.
5
partnerId
The partner id for partner integration.
nil
identifyBatchIntervalMillis
The amount of time SDK will attempt to batch intercepted identify events.
30000
flushEventsOnClose
Flushing of unsent events on app close.
true
callback
Callback function after event sent.
nil
optOut
Opt the user out of tracking.
false
(Deprecated. Use defaultTracking
autocapture
instead.)Enable tracking of default events for sessions, app lifecycles, screen views, and deep links.
DefaultTrackingOptions(sessions: true)
autocapture
Enable tracking of Autocapture events for sessions, app lifecycles, screen views, deep links, and element interactions.
AutocaptureOptions.sessions
minTimeBetweenSessionsMillis
The amount of time for session timeout.
300000
serverUrl
The server url events upload to.
https://api2.amplitude.com/2/httpapi
serverZone
The server zone to send to, will adjust server url based on this config.
US
useBatch
Whether to use batch api.
false
trackingOptions
Options to control the values tracked in SDK.
enable
enableCoppaControl
Whether to enable COPPA control for tracking options.
false
migrateLegacyData
Available in
0.4.7
+. Whether to migrate maintenance SDK data (events, user/device ID).true
offline
Available in
1.2.0+
. Whether the SDK is connected to network. Learn more here.false
Events represent how users interact with your application. For example, "Button Clicked" may be an action you want to note.
1let event = BaseEvent(2 eventType: "Button Clicked",3 eventProperties: ["my event prop key": "my event prop value"]4)5amplitude.track(event: event)
1AMPBaseEvent* event = [AMPBaseEvent initWithEventType:@"Button Clicked"2 eventProperties:@{@"my event prop key": @"my event prop value"}];3 4[amplitude track:event];
Another way to instrument basic tracking event.
1amplitude.track(2 eventType: "Button Clicked",3 eventProperties: ["my event prop key": "my event prop value"]4)
1[amplitude track:@"Button Clicked" eventProperties:@{2 @"my event prop key": @"my event prop value"3}];
Starting from release v0.4.0, identify events with only set operations will be batched and sent with fewer events. This change won't affect running the set operations. There is a config identifyBatchIntervalMillis
for managing the interval to flush the batched identify intercepts.
Identify is for setting the user properties of a particular user without sending any event. The SDK supports the operations set
, setOnce
, unset
, add
, append
, prepend
, preInsert
, postInsert
, and remove
on individual user properties. Declare the operations via a provided Identify interface. You can chain together multiple operations in a single Identify object. The Identify object is then passed to the Amplitude client to send to the server.
If the Identify call is sent after the event, the results of operations will be visible immediately in the dashboard user's profile area, but it will not appear in chart result until another event is sent after the Identify call. The identify call only affects events going forward. More details here.
You can handle the identity of a user using the identify methods. Proper use of these methods can connect events to the correct user as they move across devices, browsers, and other platforms. Send an identify call containing those user property operations to Amplitude server to tie a user's events with specific user properties.
1let identify = Identify()2identify.set(property: "color", value: "green")3amplitude.identify(identify: identify)
1AMPIdentify* identify = [AMPIdentify new];2[identify set:@"color" value:@"green"];3[amplitude identify:identify];
Starting from release v1.8.0, the SDK is able to track more events without manual instrumentation. It can be configured to track the following events automatically:
Autocapture options
Name
Type
Enabled by default
Description
sessions
AutocaptureOptions
Yes
Enables session tracking. If the option is set, Amplitude tracks session start and session end events otherwise, Amplitude doesn't track session events. When this setting isn't set, Amplitude tracks
sessionId
only. See Track sessions for more information.
appLifecycles
AutocaptureOptions
No
Enables application lifecycle events tracking. If the option is set, Amplitude tracks application installed, application updated, application opened, and application backgrounded events. Event properties tracked include:
[Amplitude] Version
, [Amplitude] Build
, [Amplitude] Previous Version
, [Amplitude] Previous Build
, [Amplitude] From Background
. See Track application lifecycles for more information.
screenViews
AutocaptureOptions
No
Enables screen views tracking. If the option is set, Amplitude tracks screen viewed events. Event properties tracked include:
[Amplitude] Screen Name
. See Track screen views for more information.
elementInteractions
AutocaptureOptions
No
Enables element interaction tracking. If the option is set, Amplitude tracks user interactions with
UIControl
element and UIGestureRecognizer
. Event properties tracked include: [Amplitude] Action
, [Amplitude] Target View Class
, [Amplitude] Target Text
, [Amplitude] Action Method
, [Amplitude] Gesture Recognizer
, [Amplitude] Hierarchy
, [Amplitude] Accessibility Identifier
, [Amplitude] Accessibility Label
, [Amplitude] Screen Name
. See Track element interactions for more information.
You can configure Amplitude to start tracking Autocapture events. Otherwise, you can omit the configuration to keep only session tracking enabled.
autocapture
configuration accepts an OptionSet
with AutocaptureOptions
values.
1let amplitude = Amplitude(configuration: Configuration(2 apiKey: "API_KEY",3 autocapture: [.sessions, .appLifecycles, .screenViews]4))
By default, if the autocapture
configuration isn't explicitly set during Configuration
initialization, configuration.autocapture
will automatically include AutocaptureOptions.sessions
.
If you want to prevent automatic session events capture, set autocapture
without the AutocaptureOptions.sessions
option.
1let amplitude = Amplitude(configuration: Configuration(2 apiKey: "API_KEY",3 autocapture: .appLifecycles // or use `[]` to disable Autocapture.4))
autocapture
configuration accepts an Array
of AutocaptureOptions
values.
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];2configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[3 AMPAutocaptureOptions.sessions,4 AMPAutocaptureOptions.appLifecycles,5 AMPAutocaptureOptions.screenViews6]];7Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
By default, if the autocapture
configuration isn't explicitly set during Configuration
initialization, configuration.autocapture
will automatically include AutocaptureOptions.sessions
.
If you want to prevent automatic session events capture, set autocapture
without the AutocaptureOptions.sessions
option.
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];2configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[AMPAutocaptureOptions.appLifecycles]]; // or use an empty array to disable Autocapture.3Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Amplitude enables session tracking by default. Include AutocaptureOptions.sessions
in the autocapture
configuration to explicitly configure the SDK to track session events or to enable session event tracking along with other Autocapture configurations.
1let amplitude = Amplitude(configuration: Configuration(2 apiKey: "API_KEY",3 autocapture: .sessions4))
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];2configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[AMPAutocaptureOptions.sessions]];3Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
For more information about session tracking, see User sessions.
trackingSessionEvents
is deprecated and replaced with the AutocaptureOptions.sessions
option of the autocapture
configuration.
You can enable Amplitude to start tracking application lifecycle events by including AutocaptureOptions.appLifecycles
in the autocapture
configuration.
1let amplitude = Amplitude(configuration: Configuration(2 apiKey: "API_KEY",3 autocapture: .appLifecycles4))
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];2configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[AMPAutocaptureOptions.appLifecycles]];3Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
When you enable this setting, Amplitude tracks the following events:
[Amplitude] Application Installed
, this event fires when a user opens the application for the first time right after installation, by observing the UIApplicationDidFinishLaunchingNotification
notification underneath.[Amplitude] Application Updated
, this event fires when a user opens the application after updating the application, by observing the UIApplicationDidFinishLaunchingNotification
notification underneath.[Amplitude] Application Opened
, this event fires when a user launches or foregrounds the application after the first open, by observing the UIApplicationDidFinishLaunchingNotification
or UIApplicationWillEnterForegroundNotification
notification underneath.[Amplitude] Application Backgrounded
, this event fires when a user backgrounds the application, by observing the UIApplicationDidEnterBackgroundNotification
notification underneath.You can enable Amplitude to start tracking screen view events by including AutocaptureOptions.screenViews
in the autocapture
configuration.
This feature is supported in UIKit. For SwiftUI, track the corresponding event manually.
1// UIKit 2let amplitude = Amplitude(configuration: Configuration( 3 apiKey: "API_KEY", 4 autocapture: .screenViews 5)) 6 7// Swift UI 8let amplitude = Amplitude(configuration: Configuration( 9 apiKey: "API_KEY",10 autocapture: []11))12amplitude.track(ScreenViewedEvent(screenName: "Screen Name"))
1// UIKit2AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];3configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[AMPAutocaptureOptions.screenViews]];4Amplitude* amplitude = [Amplitude initWithConfiguration:screenViews];5 6// Swift UI7configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[]];8[amplitude track:[AMPScreenViewedEvent initWithScreenName:@"Screen Name"]];
When you enable this setting, Amplitude tracks the [Amplitude] Screen Viewed
event and sets the screen name property of this event to the name of the top-most view controller's class. Amplitude reads this value from the controller class metadata viewDidAppear
method swizzling.
Deeplink tracking isn't automated. To track deeplinks, track the corresponding events.
1let amplitude = Amplitude(configuration: Configuration(2 apiKey: "API_KEY"3))4 5amplitude.track(DeepLinkOpenedEvent(url: URL()))6amplitude.track(DeepLinkOpenedEvent(url: "url", referrer:"referrer"))7amplitude.track(DeepLinkOpenedEvent(activity: activity))
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];2Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];3 4[amplitude track:[AMPDeepLinkOpenedEvent initWithUrl:@"url"]];5[amplitude track:[AMPDeepLinkOpenedEvent initWithUrl:@"url" referrer:@"referrer"]];6[amplitude track:[AMPDeepLinkOpenedEvent initWithActivity:activity]];
Amplitude tracks the [Amplitude] Deep Link Opened
event with the URL and referrer information.
Amplitude can track user interactions with UIControl
elements and UIGestureRecognizer
objects in UIKit
applications. To enable this option, include AutocaptureOptions.elementInteractions
in the autocapture
configuration.
The AutocaptureOptions.elementInteractions
option is available as a beta release for early feedback. Try it out and share your thoughts on our GitHub.
1let amplitude = Amplitude(configuration: Configuration(2 apiKey: "API_KEY",3 autocapture: .elementInteractions4))
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];2configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[AMPAutocaptureOptions.elementInteractions]];3Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
After enabling this setting, Amplitude will track the [Amplitude] Element Interacted
event whenever a user interacts with an element in the application. The SDK swizzles the UIApplication.sendAction(_:to:from:for:)
method and the UIGestureRecognizer.state
property setter to instrument UIControl
action methods and UIGestureRecognizer
within the application, respectively.
Event Properties Descriptions
Event property
Description
[Amplitude] Action
The action that triggered the event. Defaults to
touch
.
[Amplitude] Target View Class
The name of the target view class.
[Amplitude] Target Text
The title of the target
UIControl
element.
[Amplitude] Target Accessibility Label
The accessibility label of the target element.
[Amplitude] Target Accessibility Identifier
The accessibility identifier of the target element.
[Amplitude] Action Method
The name of the function or method that is triggered when the interaction occurs.
[Amplitude] Gesture Recognizer
The name of the
UIGestureRecognizer
class that recognizes the interaction.
[Amplitude] Hierarchy
A nested hierarchy of the target view's class inheritance, from the most specific to the most general.
[Amplitude] Screen Name
See Track screen views.
Currently, Amplitude does not supports tracking user interactions with UI elements in SwiftUI.
Amplitude supports assigning users to groups and performing queries, such as Count by Distinct, on those groups. If at least one member of the group has performed the specific event, then the count includes the group.
For example, you want to group your users based on what organization they're in by using an 'orgId'. Joe is in 'orgId' '10', and Sue is in 'orgId' '15'. Sue and Joe both perform a certain event. You can query their organizations in the Event Segmentation Chart.
When setting groups, define a groupType
and groupName
. In the previous example, 'orgId' is the groupType
and '10' and '15' are the values for groupName
. Another example of a groupType
could be 'sport' with groupName
values like 'tennis' and 'baseball'.
Setting a group also sets the groupType:groupName
as a user property, and overwrites any existing groupName
value set for that user's groupType, and the corresponding user property value. groupType
is a string, and groupName
can be either a string or an array of strings to indicate that a user is in multiple groups.
If Joe is in 'orgId' '15', then the groupName
would be '15'.
1// set group with a single group name2amplitude.setGroup(groupType: "orgId", groupName: "15")
1// set group with a single group name2[amplitude setGroup:@"orgId" groupName:@"15"];
If Joe is in 'orgId' 'sport', then the groupName
would be '["tennis", "soccer"]'.
1// set group with multiple group names2amplitude.setGroup(groupType: "sport", groupName: ["tennis", "soccer"])
1// set group with multiple group names2[amplitude setGroup:@"sport" groupNames:@[@"tennis", @"soccer"]];
You can also set event-level groups by passing an Event
Object with groups
to track
. With event-level groups, the group designation applies only to the specific event being logged, and doesn't persist on the user unless you explicitly set it with setGroup
.
1amplitude.track(2 event: BaseEvent(3 eventType: "event type",4 eventProperties: [5 "eventPropertyKey": "eventPropertyValue"6 ],7 groups: ["orgId": "15"]8 )9)
1AMPBaseEvent* event = [AMPBaseEvent initWithEventType:@"event type"2 eventProperties:@{@"eventPropertyKey": @"eventPropertyValue"}];3[event.groups set:@"orgId" value:@"15"];4[amplitude track:event];
Use the Group Identify API to set or update the properties of particular groups. Keep these considerations in mind:
The groupIdentify
method accepts a group type string parameter and group name object parameter, and an Identify object that's applied to the group.
1let groupType = "plan"2let groupName = "enterprise"3let identify = Identify().set(property: "key", value: "value")4amplitude.groupIdentify(groupType: groupType, groupName: groupProperty, identify: identify)
1NSString* groupType = @"plan";2NSString* groupName = @"enterprise";3AMPIdentify* identify = [AMPIdentify new];4[identify set:@"key" value:@"value"];5[amplitude groupIdentify:groupType groupName:groupName identify:identify];
Amplitude can track revenue generated by a user. Revenue is tracked through distinct revenue objects, which have special fields that are used in Amplitude's Event Segmentation and Revenue LTV charts. This allows Amplitude to automatically display data relevant to revenue in the platform. Revenue objects support the following special properties, as well as user-defined properties through the eventProperties
field.
1let revenue = Revenue()2revenue.price = 3.993revenue.quantity = 34revenue.productId = "com.company.productId"5amplitude.revenue(revenue: revenue)
1AMPRevenue* revenue = [AMPRevenue new];2revenue.price = 3.99;3revenue.quantity = 3;4revenue.productId = @"com.company.productId";5[amplitude revenue:revenue];
Name | Description |
---|---|
productId |
Optional. String. An identifier for the product. Amplitude recommends something like the Google Play Store product ID. Defaults to null . |
quantity |
Required. Integer. The quantity of products purchased. Note: revenue = quantity * price. Defaults to 1 |
price |
Required. Double. The price of the products purchased, and this can be negative. Note: revenue = quantity * price. Defaults to null . |
revenueType |
Optional, but required for revenue verification. String. The revenue type (for example, tax, refund, income). Defaults to null . |
receipt |
Optional. String. The receipt identifier of the revenue. For example, "123456". Defaults to null . |
receiptSignature |
Optional, but required for revenue verification. String. Defaults to null . |
If your app has its login system that you want to track users with, you can call setUserId
at any time.
1amplitude.setUserId(userId: "user@amplitude.com")
1[amplitude setUserId:@"user@amplitude.com"];
You can assign a new device ID using deviceId
. When setting a custom device ID, make sure the value is sufficiently unique. Amplitude recommends using a UUID.
1amplitude.setDeviceId(NSUUID().uuidString)
1[amplitude setDeviceId:[[NSUUID UUID] UUIDString]];
This feature supports Swift, but not Objective C
If you don't want to store the data in the Amplitude-defined location, you can customize your own storage by implementing the Storage protocol and setting the storageProvider
in your configuration.
Every iOS app gets a slice of storage just for itself, meaning that you can read and write your app's files there without worrying about colliding with other apps. By default, Amplitude uses this file storage and creates an "amplitude" prefixed folder inside the app "Documents" directory. However, if you need to expose the Documents folder in the native iOS "Files" app and don't want expose "amplitude" prefixed folder, you can customize your own storage provider to persist events on initialization.
1Amplitude(2 configuration: Configuration(3 apiKey: AMPLITUDE_API_KEY,4 storageProvider: YourOwnStorage() // YourOwnStorage() should implement Storage5 )6)
reset
is a shortcut to anonymize users after they log out, by:
userId
to null
deviceId
to a new value based on current configurationWith an empty userId
and a completely new deviceId
, the current user would appear as a brand new user in dashboard.
1amplitude.reset()
1[amplitude reset];
Plugins enable you to extend Amplitude SDK's behavior by, for example, modifying event properties (enrichment type) or sending to third-party APIs (destination type). A plugin is an object with methods setup()
and execute()
.
This method contains logic for preparing the plugin for use and has amplitude
instance as a parameter. A typical use for this method, is to instantiate plugin dependencies. This method is called when the plugin is registered to the client via amplitude.add()
.
This method contains the logic for processing events and has event
instance as parameter. If used as enrichment type plugin, the expected return value is the modified/enriched event. If used as a destination type plugin, the expected return value is null
. This method is called for each event, including Identify, GroupIdentify and Revenue events, that's instrumented using the client interface.
Here's an example of a plugin that modifies each event that's instrumented by adding extra event property.
1class EnrichmentPlugin: Plugin { 2 let type: PluginType 3 var amplitude: Amplitude? 4 5 init() { 6 self.type = PluginType.enrichment 7 } 8 9 func setup(amplitude: Amplitude) {10 self.amplitude = amplitude11 }12 13 func execute(event: BaseEvent?) -> BaseEvent? {14 event?.sessionId = -115 if event?.eventProperties == nil {16 event?.eventProperties = [:]17 }18 event?.eventProperties?["event prop key"] = "event prop value"19 return event20 }21}22 23amplitude.add(plugin: EnrichmentPlugin())
1[amplitude add:[AMPPlugin initWithType:AMPPluginTypeEnrichment2 execute:^AMPBaseEvent* _Nullable(AMPBaseEvent* _Nonnull event) {3 event.sessionId = -1;4 [event.eventProperties set:@"event prop key" value:@"event prop value"];5 return event;6}]];
In destination plugins, you can overwrite the track()
, identify()
, groupIdentify()
, revenue()
, and flush()
functions.
Objective-C supports flush()
and general execute()
functions.
1class TestDestinationPlugin: DestinationPlugin { 2 override func track(event: BaseEvent) -> BaseEvent? { 3 return event 4 } 5 6 override func identify(event: IdentifyEvent) -> IdentifyEvent? { 7 return event 8 } 9 10 override func groupIdentify(event: GroupIdentifyEvent) -> GroupIdentifyEvent? {11 return event12 }13 14 override func revenue(event: RevenueEvent) -> RevenueEvent? {15 return event16 }17 18 override func flush() {19 }20 21 override func setup(amplitude: Amplitude) {22 self.amplitude = amplitude23 }24 25 override func execute(event: BaseEvent?) -> BaseEvent? {26 return event27 }28}
1[amplitude add:[AMPPlugin initWithType:AMPPluginTypeDestination 2 execute:^AMPBaseEvent* _Nullable(AMPBaseEvent* _Nonnull event) { 3 if ([event.eventType isEqualToString:@"$identify"]) { 4 // ... 5 } else if ([event.eventType isEqualToString:@"$groupidentify"]) { 6 // ... 7 } else if ([event.eventType isEqualToString:@"revenue_amount"]) { 8 // ... 9 } else {10 // ...11 }12 return nil;13} flush:^() {14 // ...15}]];
Ensure that the configuration and payload are accurate and check for any unusual messages during the debugging process. If everything appears to be right, check the value of flushQueueSize
or flushIntervalMillis
. Events are queued and sent in batches by default, which means they are not immediately dispatched to the server. Ensure that you have waited for the events to be sent to the server before checking for them in the charts.
loggerProvider
class from the LoggerProvider
and implement your own logic, such as logging error message in server in a production environment.Take advantage of a Destination Plugin to print out the configuration value and event payload before sending them to the server. You can set the logLevel to debug, copy the following TroubleShootingPlugin
into your project, add the plugin into the Amplitude instance.
SwiftUI TroubleShootingPlugin example.
The event callback executes after the event is sent, for both successful and failed events. Use this method to monitor the event status and message. For more information, see configuration > callback.
Amplitude starts a session when the app is brought into the foreground or when an event is tracked in the background. A session ends when the app remains in the background for more than the time set by setMinTimeBetweenSessionsMillis()
without any event being tracked. Note that a session will continue for the entire time the app is in the foreground no matter whether session tracking is enabled by configuration.defaultTracking
, configuration.autocapture
or not.
When the app enters the foreground, Amplitude tracks a session start, and starts a countdown based on setMinTimeBetweenSessionsMillis()
. Amplitude extends the session and restarts the countdown any time it tracks a new event. If the countdown expires, Amplitude waits until the next event to track a session end event.
Amplitude doesn't set user properties on session events by default. To add these properties, use identify()
and setUserId()
. Amplitude aggregates the user property state and associates the user with events based on device_id
or user_id
.
Due to the way in which Amplitude manages sessions, there are scenarios where the SDK works expected but it may appear as if events are missing or session tracking is inaccurate:
event['$skip_user_properties_sync']
to true
on the session end event, which prevents Amplitude from synchronizing properties for that specific event. See $skip_user_properties_sync in the Converter Configuration Reference article to learn more.Amplitude groups events together by session. Events that are logged within the same session have the same session_id
. Sessions are handled automatically so you don't have to manually call startSession()
or endSession()
.
You can adjust the time window for which sessions are extended. The default session expiration time is five minutes.
1let amplitude = Amplitude(2 configuration: Configuration(3 apiKey: AMPLITUDE_API_KEY,4 minTimeBetweenSessionsMillis: 10005 )6)
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];2configuration.minTimeBetweenSessionsMillis = 1000;3Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
trackingSessionEvents
is deprecated and replaced with the AutocaptureOptions.sessions
option of autocapture
.
You can also track events as out-of-session. Out-of-session events have a sessionId
of -1
and behave as follows:
sessionId
for subsequent events.A potential use case is for events tracked from push notifications, which are usually external to the customers app usage.
Set the sessionId
to -1
in EventOptions
to mark an event as out-of-session when you call track(event, options)
or identify(identify, options)
.
1let outOfSessionOptions = EventOptions(sessionId: -1) 2 3amplitude.identify( 4 event: Identify().set(property: "user-prop", value: true), 5 options: outOfSessionOptions 6) 7 8amplitude.track( 9 event: BaseEvent(eventType: "Button Clicked"),10 options: outOfSessionOptions11)
1AMPEventOptions* outOfSessionOptions = [AMPEventOptions new];2outOfSessionOptions.sessionId = -1;3 4AMPIdentify* identify = [AMPIdentify new];5[identify set:@"user-prop" value:YES];6[amplitude identify:identify options:outOfSessionOptions];7 8AMPBaseEvent* event = [AMPBaseEvent initWithEventType:@"Button Clicked"];9[amplitude track:event options:outOfSessionOptions];
control the level of logs that print to the developer console.
Set the log level logLevel
with the level you want.
1let amplitude = Amplitude(configuration: Configuration(2 apiKey: AMPLITUDE_API_KEY,3 logLevel: LogLevelEnum.LOG4))
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];2configuration.logLevel = AMPLogLevelLOG;3Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Amplitude merges user data, so any events associated with a known userId
or deviceId
are linked the existing user.
If a user logs out, Amplitude can merge that user's logged-out events to the user's record. You can change this behavior and log those events to an anonymous user instead.
To log events to an anonymous user:
userId
to null.deviceId
.Events coming from the current user or device appear as a new user in Amplitude. Note: If you do this, you can't see that the two users were using the same device.
1amplitude.reset()
1[amplitude reset];
By default the iOS SDK tracks several user properties such as carrier
, city
, country
, ip_address
, language
, and platform
.
Use the provided TrackingOptions
interface to customize and toggle individual fields.
Before initializing the SDK with your apiKey, create a TrackingOptions
instance with your configuration and set it on the SDK instance.
1let trackingOptions = TrackingOptions()2trackingOptions.disableTrackCity().disableTrackIpAddress()3let amplitude = Amplitude(4 configuration: Configuration(5 apiKey: AMPLITUDE_API_KEY,6 trackingOptions: trackingOptions7 )8)
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];2[configuration.trackingOptions disableTrackCity];3[configuration.trackingOptions disableTrackIpAddress];4Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Tracking for each field can be individually controlled, and has a corresponding method (for example, disableCountry
, disableLanguage
).
Method | Description |
---|---|
disableTrackCarrier() |
Disable tracking of device's carrier |
disableTrackCity() |
Disable tracking of user's city |
disableTrackCountry() |
Disable tracking of user's country |
disableTrackDeviceModel() |
Disable tracking of device model |
disableTrackDeviceManufacturer() |
Disable tracking of device manufacturer |
disableTrackDMA() |
Disable tracking of user's designated market area (DMA) |
disableTrackIpAddress() |
Disable tracking of user's IP address |
disableTrackLanguage() |
Disable tracking of device's language |
disableTrackIDFV() |
|
disableTrackOsName() |
Disable tracking of device's OS Name |
disableTrackOsVersion() |
Disable tracking of device's OS Version |
disableTrackPlatform() |
Disable tracking of device's platform |
disableTrackRegion() |
Disable tracking of user's region |
disableTrackVersionName() |
Disable tracking of your app's version name |
Using TrackingOptions
only prevents default properties from being tracked on newly created projects, where data has not yet been sent. If you have a project with existing data that you want to stop collecting the default properties for, get help in the Amplitude Community. Disabling tracking doesn't delete any existing data in your project.
Amplitude determines the user's mobile carrier using CTTelephonyNetworkInfo
, which returns the registered operator of the sim
.
COPPA (Children's Online Privacy Protection Act) restrictions on IDFA, IDFV, city, IP address and location tracking can all be enabled or disabled at one time. Apps that ask for information from children under 13 years of age must comply with COPPA.
1let amplitude = Amplitude(2 configuration: Configuration(3 apiKey: AMPLITUDE_API_KEY,4 enableCoppaControl: true5 )6)
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];2configuration.enableCoppaControl = true;3Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Advertiser ID (also referred to as IDFA) is a unique identifier provided by the iOS and Google Play stores. As it's unique to every person and not just their devices, it's useful for mobile attribution.
Mobile attribution is the attribution of an installation of a mobile app to its original source (such as ad campaign, app store search). Mobile apps need permission to ask for IDFA, and apps targeted to children can't track at all. Consider using IDFV, device ID, or an email login system when IDFA isn't available.
To retrieve the IDFA and add it to the tracking events, you can follow this example plugin to implement your own plugin.
The SDK initializes the device ID in the following order, with the device ID being set to the first valid value encountered:
setDeviceId()
A single user may have multiple devices, each having a different device ID. To ensure coherence, set the user ID consistently across all these devices. Even though the device IDs differ, Amplitude can still merge them into a single Amplitude ID, thus identifying them as a unique user.
It's possible for multiple devices to have the same device ID when a user switches to a new device. When transitioning to a new device, users often transfer their applications along with other relevant data. The specific transferred content may vary depending on the application. In general, it includes databases and file directories associated with the app. However, the exact items included depend on the app's design and the choices made by the developers. If databases or file directories have been backed up from one device to another, the device ID stored within them may still be present. Consequently, if the SDK attempts to retrieve it during initialization, different devices might end up using the same device ID.
Use the helper method getDeviceId()
to get the value of the current deviceId
.
1let deviceId = amplitude.getDeviceId()
1NSString* deviceId = [amplitude getDeviceId];
To set the device, see custom device ID.
Amplitude converts the IP of a user event into a location (GeoIP lookup) by default. This information may be overridden by an app's own tracking solution or user data.
Users may wish to opt out of tracking entirely, which means Amplitude doesn't track any of their events or browsing history. OptOut
provides a way to fulfill a user's requests for privacy.
1let amplitude = Amplitude(2 configuration: Configuration(3 apiKey: AMPLITUDE_API_KEY,4 optOut: true5 )6)
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];2configuration.optOut = true;3Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Implements a customized loggerProvider
class from the LoggerProvider, and pass it in the configuration during the initialization to help with collecting any error messages from the SDK in a production environment.
1class SampleLogger: Logger { 2 typealias LogLevel = LogLevelEnum 3 4 var logLevel: Int 5 6 init(logLevel: Int = LogLevelEnum.OFF.rawValue) { 7 self.logLevel = logLevel 8 } 9 10 func error(message: String) {11 // TODO: handle error message12 }13 14 func warn(message: String) {15 // TODO: handle warn message16 }17 18 func log(message: String) {19 // TODO: handle log message20 }21 22 func debug(message: String) {23 // TODO: handle debug message24 }25}26 27let amplitude = Amplitude(28 configuration: Configuration(29 apiKey: AMPLITUDE_API_KEY,30 loggerProvider: SampleLogger()31 )32)
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY]; 2configuration.loggerProvider = ^(NSInteger logLevel, NSString* _Nonnull message) { 3 switch(logLevel) { 4 case AMPLogLevelERROR: 5 // TODO: handle error message 6 break; 7 case AMPLogLevelWARN: 8 // TODO: handle warn message 9 break;10 case AMPLogLevelLOG:11 // TODO: handle log message12 break;13 case AMPLogLevelDEBUG:14 // TODO: handle debug message15 break;16 }17};18Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
iOS automatically protects application data by storing each apps data in its own secure directory. This directory is usually not accessible by other applications. However, if a device is jailbroken, apps are granted root access to all directories on the device.
To prevent other apps from accessing your apps Amplitude data on a jailbroken device, Amplitude recommends setting a unique instance name for your SDK. This creates a unique database isolates it from other apps.
1let amplitude = Amplitude(2 configuration: Configuration(3 apiKey: "API-KEY",4 instanceName: "my-unqiue-instance-name"5 )6)
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API-KEY"2 instanceName:@"my-unqiue-instance-name"];3Amplitude* amplitude = [Amplitude instanceWithConfiguration:configuration];
Beginning with version 1.3.0, the Amplitude iOS Swift SDK supports offline mode. The SDK checks network connectivity every time it tracks an event. If the device is connected to network, the SDK schedules a flush. If not, it saves the event to storage. The SDK also listens for changes in network connectivity and flushes all stored events when the device reconnects.
To disable offline mode, add offline: NetworkConnectivityCheckerPlugin.Disabled
on initialization as shown below.
1let amplitude = Amplitude(2 configuration: Configuration(3 apiKey: "API-KEY",4 offline: NetworkConnectivityCheckerPlugin.Disabled5 )6)
1AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];2configuration.offline = AMPNetworkConnectivityCheckerPlugin.Disabled;3Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
You can also implement you own offline logic:
amplitude.configuration.offline
by yourself.Starting December 8, 2020, Apple requires a privacy manifest file for all new apps and app updates. Apple expects to make this mandatory in the Spring of 2024. As Amplitude is a third-party to your app, you need to ensure you properly disclose to your users the ways you use Amplitude in regards to their data.
Amplitude sets privacy manifest based on a default configuration. Update the privacy manifest according to your configuration and your app.
Tracking refers to the act of linking user or device data collected from your app with user or device data collected from other companies' apps, websites, or offline properties for targeted advertising or advertising measurement purposes. For more information, see Apple's article User privacy and data use.
By default, Amplitude doesn't use data for tracking. Add this field and set it to true if your app does.
Date type | Linked to user | Used for tracking | Reason for collection | Where it's tracked |
---|---|---|---|---|
Product interaction | Yes | No | Analytics | Such as app launches, taps, clicks, scrolling information, music listening data, video views, saved place in a game, video, or song, or other information about how the user interacts with the app. |
Device ID | Yes | No | Analytics | Tracked by default. Learn more here |
Coarse Location | Yes | No | Analytics | Country, region, and city based on IP address. Amplitude doesn't collect them from device GPS or location features. |
By default the SDK tracks deviceId
only. You can use setUserId()
to track userId
as well. To do so, add the "User ID" Data type. For more information about data types, see Apple's article Describing data use in privacy manifests.
If you set NSPrivacyTracking
to true then you need to provide at least one internet domain in NSPrivacyTrackingDomains
based on your configuraiton.
Domain | Description |
---|---|
https://api2.amplitude.com/2/httpapi | The default HTTP V2 endpoint. |
https://api.eu.amplitude.com/2/httpapi | EU endpoint if configuration.serverZone = EU . |
https://api2.amplitude.com/batch | Batch endpoint if configuration.useBatch = true . |
https://api.eu.amplitude.com/batch | Batch EU endpoint if configuration.useBatch = true and configuration.serverZone = EU . |
The SDK only uses userDefaults
API for identity storage.
Follow the steps on how to create your app's privacy.
Thanks for your feedback!
July 23rd, 2024
Need help? Contact Support
Visit Amplitude.com
Have a look at the Amplitude Blog
Learn more at Amplitude Academy
© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.