iOS SDK
This is the official documentation for the Amplitude Analytics iOS SDK.
Carrier cannot be tracked in iOS 16+
The SDK fetches carrier information by using serviceSubscriberCellularProviders
and CTCarrier
which are deprecated with no replacement starting from iOS 16. Amplitude will keep updated with Apple and re-enable carrier tracking as soon as Apple releases a replacement.
SDK bundle size
Use the Cocoapods size measurement tool to view and find the size of the SDK bundle. Clone this repo and go in the root directory. Open your terminal and type, for example,
./measure_cocoapod_size.py --cocoapods AmplitudeSwift:1.0.0
.
Minimum versions
For the minimum supported platform versions of this package, see Package.swift
on GitHub.
Getting started¶
Use this quickstart guide to get started with Amplitude iOS SDK.
Usage¶
Initialize¶
You must initialize the SDK before you can instrument. The API key for your Amplitude project is required.
let amplitude = Amplitude(configuration: Configuration(
apiKey: AMPLITUDE_API_KEY
))
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
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 |
defaultTracking |
Enable tracking of default events for sessions, app lifecycle, screen views, and deep links. | DefaultTrackingOptions(sessions: true) |
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 |
track
¶
Events represent how users interact with your application. For example, "Button Clicked" may be an action you want to note.
let event = BaseEvent(
eventType: "Button Clicked",
eventProperties: ["my event prop key": "my event prop value"]
)
amplitude.track(event: event)
AMPBaseEvent* event = [AMPBaseEvent initWithEventType:@"Button Clicked"
eventProperties:@{@"my event prop key": @"my event prop value"}];
[amplitude track:event];
Another way to instrument basic tracking event.
amplitude.track(
eventType: "Button Clicked",
eventProperties: ["my event prop key": "my event prop value"]
)
[amplitude track:@"Button Clicked" eventProperties:@{
@"my event prop key": @"my event prop value"
}];
identify
¶
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.
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.
Note
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. So 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.
let identify = Identify()
identify.set(property: "color", value: "green")
amplitude.identify(identify: identify)
AMPIdentify* identify = [AMPIdentify new];
[identify set:@"color" value:@"green"];
[amplitude identify:identify];
Tracking default events¶
Starting from release v0.6.0, the SDK can track more default events. You can configure it to track the following events by default:
Tracking default events options
Name |
Type | Default Value | Description |
---|---|---|---|
defaultTracking.sessions |
Optional. boolean |
true |
Enables session tracking. This configuration replaces trackingSessionEvents . If value is true , Amplitude tracks session start and session end events.See Tracking sessions for more information. |
defaultTracking.appLifecycles |
Optional. boolean |
false |
Enables application lifecycle events tracking. If value is true , Amplitude tracks application installed, application updated, application opened, and application backgrounded events.Event properties tracked includes: [Amplitude] Version ,[Amplitude] Build ,[Amplitude] Previous Version , [Amplitude] Previous Build , [Amplitude] From Background See Tracking application lifecycles for more information. |
defaultTracking.screenViews |
Optional. boolean |
false |
Enables screen views tracking. If value is true , Amplitude tracks screen viewed events.Event properties tracked includes: [Amplitude] Screen Name See Tracking screen views for more information. |
Use the code sample below to enable the above-mentioned tracking events.
let amplitude = Amplitude(configuration: Configuration(
apiKey: "API_KEY",
defaultTracking: DefaultTrackingOptions.ALL
))
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];
configuration.defaultTracking = AMPDefaultTrackingOptions.ALL;
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Note
Amplitude may add more events in a future version, and this configuration enables tracking for those events as well.
Use the code sample below to disable tracking the above-mentioned tracking events.
let amplitude = Amplitude(configuration: Configuration(
apiKey: "API_KEY",
defaultTracking: DefaultTrackingOptions.NONE
))
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];
configuration.defaultTracking = AMPDefaultTrackingOptions.NONE;
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Customize the tracking with DefaultTrackingOptions
.
let amplitude = Amplitude(configuration: Configuration(
apiKey: "API_KEY",
defaultTracking: DefaultTrackingOptions(
sessions: true,
appLifecycles: false,
screenViews: false
)
))
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];
configuration.defaultTracking.sessions = true;
configuration.defaultTracking.appLifecycles = false;
configuration.defaultTracking.screenViews = false;
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Tracking sessions¶
Amplitude enables session tracking by default. Set defaultTracking.sessions
to true
to track session events.
let amplitude = Amplitude(configuration: Configuration(
apiKey: "API_KEY",
defaultTracking: DefaultTrackingOptions(
sessions: true
)
))
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];
configuration.defaultTracking.sessions = true;
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
For more information about session tracking, refer to User sessions.
Note
trackingSessionEvents
is deprecated and replaced with defaultTracking.sessions
.
Tracking application lifecycles¶
Set defaultTracking.appLifecycles
to true
to enable Amplitude to track application lifecycle events.
let amplitude = Amplitude(configuration: Configuration(
apiKey: "API_KEY",
defaultTracking: DefaultTrackingOptions(
appLifecycles: true
)
))
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];
configuration.defaultTracking.appLifecycles = true;
Amplitude* 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 theUIApplicationDidFinishLaunchingNotification
notification underneath.[Amplitude] Application Updated
, this event fires when a user opens the application after updating the application, by observing theUIApplicationDidFinishLaunchingNotification
notification underneath.[Amplitude] Application Opened
, this event fires when a user launches or foregrounds the application after the first open, by observing theUIApplicationDidFinishLaunchingNotification
orUIApplicationWillEnterForegroundNotification
notification underneath.[Amplitude] Application Backgrounded
, this event fires when a user backgrounds the application, by observing theUIApplicationDidEnterBackgroundNotification
notification underneath.
Tracking screen views¶
Set defaultTracking.screenViews
to true
to enable Amplitude to track screen view events.
Warning
This feature is supported in UIKit. For Swift UI, track the corresponding event manually.
// UIKit
let amplitude = Amplitude(configuration: Configuration(
apiKey: "API_KEY",
defaultTracking: DefaultTrackingOptions(
screenViews: true
)
))
// Swift UI
amplitude.configuration.defaultTracking.screenViews = false
amplitude.track(ScreenViewedEvent(screenName: "Screen Name"))
// UIKit
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];
configuration.defaultTracking.screenViews = true;
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
// Swift UI
amplitude.configuration.defaultTracking.screenViews = false;
[amplitude track:[AMPScreenViewedEvent initWithScreenName:@"Screen Name"]];
When you enable this setting, Amplitude tracks the [Amplitude] Screen Viewed
event with the screen name property. Amplitude reads this value from the controller class metadata viewDidAppear
method swizzling.
Tracking deep links¶
Deeplink tracking is not automated. To track deeplinks, track the corresponding events.
let amplitude = Amplitude(configuration: Configuration(
apiKey: "API_KEY"
))
amplitude.track(DeepLinkOpenedEvent(url: URL()))
amplitude.track(DeepLinkOpenedEvent(url: "url", referrer:"referrer"))
amplitude.track(DeepLinkOpenedEvent(activity: activity))
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API_KEY"];
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
[amplitude track:[AMPDeepLinkOpenedEvent initWithUrl:@"url"]];
[amplitude track:[AMPDeepLinkOpenedEvent initWithUrl:@"url" referrer:@"referrer"]];
[amplitude track:[AMPDeepLinkOpenedEvent initWithActivity:activity]];
Amplitude tracks the [Amplitude] Deep Link Opened
event with the URL and referrer information.
User groups¶
Feature availability
This feature is available in accounts with a Growth or Enterprise plan with the Accounts add-on.
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.
Example
If Joe is in 'orgId' '15', then the groupName
would be '15'.
// set group with a single group name
amplitude.setGroup(groupType: "orgId", groupName: "15")
// set group with a single group name
[amplitude setGroup:@"orgId" groupName:@"15"];
If Joe is in 'orgId' 'sport', then the groupName
would be '["tennis", "soccer"]'.
// set group with multiple group names
amplitude.setGroup(groupType: "sport", groupName: ["tennis", "soccer"])
// set group with multiple group names
[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
.
amplitude.track(
event: BaseEvent(
eventType: "event type",
eventProperties: [
"eventPropertyKey": "eventPropertyValue"
],
groups: ["orgId": "15"]
)
)
AMPBaseEvent* event = [AMPBaseEvent initWithEventType:@"event type"
eventProperties:@{@"eventPropertyKey": @"eventPropertyValue"}];
[event.groups set:@"orgId" value:@"15"];
[amplitude track:event];
Group identify¶
Feature availability
This feature is available in accounts with a Growth or Enterprise plan with the Accounts add-on.
Use the Group Identify API to set or update the properties of particular groups. Keep these considerations in mind:
- Updates affect only future events, and don't update historical events.
- You can track up to 5 unique group types and 10 total groups.
The groupIdentify
method accepts a group type string parameter and group name object parameter, and an Identify object that's applied to the group.
let groupType = "plan"
let groupName = "enterprise"
let identify = Identify().set(property: "key", value: "value")
amplitude.groupIdentify(groupType: groupType, groupName: groupProperty, identify: identify)
NSString* groupType = @"plan";
NSString* groupName = @"enterprise";
AMPIdentify* identify = [AMPIdentify new];
[identify set:@"key" value:@"value"];
[amplitude groupIdentify:groupType groupName:groupName identify:identify];
Track revenue¶
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.
let revenue = Revenue()
revenue.price = 3.99
revenue.quantity = 3
revenue.productId = "com.company.productId"
amplitude.revenue(revenue: revenue)
AMPRevenue* revenue = [AMPRevenue new];
revenue.price = 3.99;
revenue.quantity = 3;
revenue.productId = @"com.company.productId";
[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 . |
Custom user ID¶
If your app has its login system that you want to track users with, you can call setUserId
at any time.
amplitude.setUserId(userId: "user@amplitude.com")
[amplitude setUserId:@"user@amplitude.com"];
Custom device ID¶
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.
amplitude.setDeviceId(NSUUID().uuidString)
[amplitude setDeviceId:[[NSUUID UUID] UUIDString]];
Custom storage¶
Objective-C Not Supported
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.
Amplitude(
configuration: Configuration(
apiKey: AMPLITUDE_API_KEY,
storageProvider: YourOwnStorage() // YourOwnStorage() should implement Storage
)
)
// Custom storage is not supported in Objective-C
Reset when user logs out¶
reset
is a shortcut to anonymize users after they log out, by:
- setting
userId
tonull
- setting
deviceId
to a new value based on current configuration
With an empty userId
and a completely new deviceId
, the current user would appear as a brand new user in dashboard.
amplitude.reset()
[amplitude reset];
Amplitude SDK plugin¶
Plugins allow 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()
.
Plugin.setup¶
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()
.
Plugin.execute¶
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.
Plugin examples¶
Enrichment type plugin¶
Here's an example of a plugin that modifies each event that's instrumented by adding extra event property.
class EnrichmentPlugin: Plugin {
let type: PluginType
var amplitude: Amplitude?
init() {
self.type = PluginType.enrichment
}
func setup(amplitude: Amplitude) {
self.amplitude = amplitude
}
func execute(event: BaseEvent?) -> BaseEvent? {
event?.sessionId = -1
if event?.eventProperties == nil {
event?.eventProperties = [:]
}
event?.eventProperties?["event prop key"] = "event prop value"
return event
}
}
amplitude.add(plugin: EnrichmentPlugin())
[amplitude add:[AMPPlugin initWithType:AMPPluginTypeEnrichment
execute:^AMPBaseEvent* _Nullable(AMPBaseEvent* _Nonnull event) {
event.sessionId = -1;
[event.eventProperties set:@"event prop key" value:@"event prop value"];
return event;
}]];
Destination type plugin¶
In destination plugin, you are able to overwrite the track(), identify(), groupIdentify(), revenue(), flush() functions.
Objective-C Not Supported
Objective-C supports flush()
and general execute()
functions.
class TestDestinationPlugin: DestinationPlugin {
override func track(event: BaseEvent) -> BaseEvent? {
return event
}
override func identify(event: IdentifyEvent) -> IdentifyEvent? {
return event
}
override func groupIdentify(event: GroupIdentifyEvent) -> GroupIdentifyEvent? {
return event
}
override func revenue(event: RevenueEvent) -> RevenueEvent? {
return event
}
override func flush() {
}
override func setup(amplitude: Amplitude) {
self.amplitude = amplitude
}
override func execute(event: BaseEvent?) -> BaseEvent? {
return event
}
}
[amplitude add:[AMPPlugin initWithType:AMPPluginTypeDestination
execute:^AMPBaseEvent* _Nullable(AMPBaseEvent* _Nonnull event) {
if ([event.eventType isEqualToString:@"$identify"]) {
// ...
} else if ([event.eventType isEqualToString:@"$groupidentify"]) {
// ...
} else if ([event.eventType isEqualToString:@"revenue_amount"]) {
// ...
} else {
// ...
}
return nil;
} flush:^() {
// ...
}]];
Troubleshooting and Debugging¶
How to debug¶
Please 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.
Log¶
- Set the log level to debug to collect useful information during debugging. More details.
- Customize
loggerProvider
class from theLoggerProvider
and implement your own logic, such as logging error message in server in a production environment. More details.
Plugins¶
You can 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 amplitude instance.
Event Callback¶
The event callback will be executed after the event has been sent, for both successful and failed events. You can use this method to monitor the event status and message. Check how to set callback under configuration > callback.
Common Issues¶
Please refer to this document for additional common issues in general.
Advanced topics¶
User sessions¶
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.trackingSessionEvents
or configuration.defaultTracking.sessions
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:
- If a user doesn't return to the app, Amplitude does not track a session end event to correspond with a session start event.
- If you track an event in the background, it's possible that Amplitude perceives the session length to be longer than the user spends on the app in the foreground.
- If you modify user properties between the last event and the session end event, the session end event reflects the updated user properties, which may differ from other properties associated with events in the same session. To address this, use an enrichment plugin to set
event['$skip_user_properties_sync']
totrue
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 30 minutes.
let amplitude = Amplitude(
configuration: Configuration(
apiKey: AMPLITUDE_API_KEY,
minTimeBetweenSessionsMillis: 1000
)
)
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];
configuration.minTimeBetweenSessionsMillis = 1000;
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
By default, Amplitude automatically sends the '[Amplitude] Start Session' and '[Amplitude] End Session' events. Even though these events aren't sent, sessions are still tracked by using session_id
.
You can also disable those session events.
let amplitude = Amplitude(configuration: Configuration(
apiKey: AMPLITUDE_API_KEY,
defaultTracking: DefaultTrackingOptions(
sessions: false
)
))
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];
configuration.defaultTracking.sessions = false;
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Note
trackingSessionEvents
is deprecated and replaced with defaultTracking.sessions
.
Set custom user ID¶
If your app has its login system that you want to track users with, you can call setUserId
at any time.
amplitude.setUserId(userId: "USER_ID")
[amplitude setUserId:@"USER_ID"];
Don't assign users a user ID that could change, because each unique user ID is a unique user in Amplitude. Learn more about how Amplitude tracks unique users in the Help Center.
Log level¶
You can control the level of logs that print to the developer console.
- 'OFF': Suppresses all log messages.
- 'ERROR': Shows error messages only.
- 'WARN': Shows error messages and warnings. This level logs issues that might be a problem and cause some oddities in the data. For example, this level would display a warning for properties with null values.
- 'LOG': Shows informative messages about events.
- 'DEBUG': Shows error messages, warnings, and informative messages that may be useful for debugging.
Set the log level logLevel
with the level you want.
let amplitude = Amplitude(configuration: Configuration(
apiKey: AMPLITUDE_API_KEY,
logLevel: LogLevelEnum.LOG
))
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];
configuration.logLevel = AMPLogLevelLOG;
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Logged out and anonymous users¶
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:
- Set the
userId
to null. - Generate a new
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.
amplitude.reset()
[amplitude reset];
Disable tracking¶
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.
let trackingOptions = TrackingOptions()
trackingOptions.disableTrackCity().disableTrackIpAddress()
let amplitude = Amplitude(
configuration: Configuration(
apiKey: AMPLITUDE_API_KEY,
trackingOptions: trackingOptions
)
)
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];
[configuration.trackingOptions disableTrackCity];
[configuration.trackingOptions disableTrackIpAddress];
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Tracking for each field can be individually controlled, and has a corresponding method (for example, disableCountry
, disableLanguage
).
Method |
Description |
---|---|
disableAdid() |
Disable tracking of Google ADID |
disableCarrier() |
Disable tracking of device's carrier |
disableCity() |
Disable tracking of user's city |
disableCountry() |
Disable tracking of user's country |
disableDeviceBrand() |
Disable tracking of device brand |
disableDeviceModel() |
Disable tracking of device model |
disableDma() |
Disable tracking of user's designated market area (DMA). |
disableIpAddress() |
Disable tracking of user's IP address |
disableLanguage() |
Disable tracking of device's language |
disableLatLng() |
Disable tracking of user's current latitude and longitude coordinates |
disableOsName() |
Disable tracking of device's OS Name |
disableOsVersion() |
Disable tracking of device's OS Version |
disablePlatform() |
Disable tracking of device's platform |
disableRegion() |
Disable tracking of user's region. |
disableVersionName() |
Disable tracking of your app's version name |
Note
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.
Carrier¶
Amplitude determines the user's mobile carrier using CTTelephonyNetworkInfo
, which returns the registered operator of the sim
.
COPPA control¶
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.
let amplitude = Amplitude(
configuration: Configuration(
apiKey: AMPLITUDE_API_KEY,
enableCoppaControl: true
)
)
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];
configuration.enableCoppaControl = true;
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Advertiser ID¶
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.
Device ID lifecycle¶
The SDK initializes the device ID in the following order, with the device ID being set to the first valid value encountered:
- Device ID of Amplitude instance if it’s set by
setDeviceId()
- IDFV if it exists
- A randomly generated UUID string
One user with multiple devices¶
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.
Transfer to a new device¶
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.
Get device ID¶
You can use the helper method getDeviceId()
to get the value of the current deviceId
.
let deviceId = amplitude.getDeviceId()
NSString* deviceId = [amplitude getDeviceId];
To set the device, refer to custom device ID.
Location tracking¶
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.
Opt users out of tracking¶
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.
let amplitude = Amplitude(
configuration: Configuration(
apiKey: AMPLITUDE_API_KEY,
optOut: true
)
)
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];
configuration.optOut = true;
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Set log callback¶
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.
class SampleLogger: Logger {
typealias LogLevel = LogLevelEnum
var logLevel: Int
init(logLevel: Int = LogLevelEnum.OFF.rawValue) {
self.logLevel = logLevel
}
func error(message: String) {
// TODO: handle error message
}
func warn(message: String) {
// TODO: handle warn message
}
func log(message: String) {
// TODO: handle log message
}
func debug(message: String) {
// TODO: handle debug message
}
}
let amplitude = Amplitude(
configuration: Configuration(
apiKey: AMPLITUDE_API_KEY,
loggerProvider: SampleLogger()
)
)
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY];
configuration.loggerProvider = ^(NSInteger logLevel, NSString* _Nonnull message) {
switch(logLevel) {
case AMPLogLevelERROR:
// TODO: handle error message
break;
case AMPLogLevelWARN:
// TODO: handle warn message
break;
case AMPLogLevelLOG:
// TODO: handle log message
break;
case AMPLogLevelDEBUG:
// TODO: handle debug message
break;
}
};
Amplitude* amplitude = [Amplitude initWithConfiguration:configuration];
Security¶
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, we recommend setting a unique instance name for your SDK. This will create a unique database that is isolated from other apps.
AMPConfiguration* configuration = [AMPConfiguration initWithApiKey:@"API-KEY"
instanceName:@"my-unqiue-instance-name"];
Amplitude* amplitude = [Amplitude instanceWithConfiguration:configuration];
let amplitude = Amplitude(
configuration: Configuration(
apiKey: "API-KEY",
instanceName: "my-unqiue-instance-name"
)
)
More resources¶
If you have any problems or issues with the SDK, create a GitHub issue or submit a request on Amplitude Help.
-
Session tracking is the same as supported in previous versions, which was previously enabled/disabled with the
trackingSessionEvents
configuration. ↩ -
Screen views are supported in UIKit. For Swift UI, you need to manually call the corresponding methods. ↩