Important Note:
- This article has been moved to our Developer Center, and will no longer be updated on this site. Here is the newest version of our iOS SDK Settings Guide.
This article will guide you through using Amplitude's iOS SDK to track users and events. The variables and values in red are what you will need to replace with your own. Please see our iOS SDK reference for a description of all available SDK methods and classes. For best practices on instrumenting Amplitude, see our Getting Started Guide for developers and sign up for one of our instrumentation training seminars here.
The SDK automatically pulls useful data from a user's device, including app version, phone model, operating system version, and carrier information. They are displayed as user properties in Amplitude. You can read more about them here. The source code for Amplitude's iOS SDK with the latest version is on Github - Amplitude iOS SDK.
In addition, we have a few demo applications available as resources:
- Here is a demo application that shows a simple integration.
- Here is a demo application that shows a simple integration in iOS extensions.
Starting with version 4.10.0, the SDK now also supports control for COPPA - Children's Online Privacy Protection Act. For additional information regarding SDK installation for Amplitude, please feel free to check out our Developers Centre here.
Starting with the iOS SDK version 5.0.0 macOS APP event tracking is supported. Users can now can now use the iOS SDK to instrument their Apps running on macOS. Two modes are supported:
- Pure macOS App
- Mac Catalyst (iPad App running on macOS) https://cocoapods.org/pods/Amplitude
Table of Contents
- Installation
- Tracking Events
- Tracking Sessions
- Setting Custom User IDs
- Setting Event Properties
- Setting User Properties
- Setting Group Properties
- Tracking Revenue
- Opting User Out of Logging
- Disable Automatic Tracking of User Properties
- tvOS
- Swift
- Advanced
Installation
1. Create an Amplitude account. If you have not already, go to https://amplitude.com and register for an account. Then, create an organization and a project. You will immediately receive an API Key for the project you have just created.
2. Install the SDK. There are a few options to install the iOS SDK.
- Download the source code here and extract the ZIP file.
- Alternatively, you can pull directly from GitHub here.
- If you use CocoaPods, add the following line to your Podfile, and you can also skip steps 3 and 4:
# Starting from v5.0.0, we changed the pod name to `Amplitude`.
# Since it supports iOS/tvOS/macOS now, we make it more generic.
pod 'Amplitude', '~> 5.0.0'
# Old pod name (before v5.0.0) is still supported.
pod 'Amplitude-iOS', '~> 4.5'
- If you are using Carthage, add the following line to your Cartfile and also be sure to import all the Amplitude header files:
github "amplitude/Amplitude-iOS"
#import <Amplitude/Amplitude.h>
- We also support Swfit Package Manager. Please follow the tutorial below. Please input our repository url when choosing the package. https://github.com/amplitude/Amplitude-iOS
- If you are using Swift, you should read these instructions here.
- If you are using our iOS SDK with a tvOS app, you should read the information here.
- If you are installing the SDK in an iOS extension, read the instructions here.
3. Copy. Copy the Amplitude
subfolder into the source of your project in Xcode. Check "Copy items into destination group's folder (if needed)".
4. Enable the SQLite library. Amplitude's iOS SDK requires the SQLite library, which is included in iOS but requires an additional build flag to enable. In your project's Build Settings
and your Target's Build Settings
, add the flag -lsqlite3.0
under Linking
-> Other Linker Flags
.
5. Import. In every file that uses analytics, import Amplitude.h at the top:
#import "Amplitude.h"
6. Initialize the SDK with your API Key. If you are implementing tracking for iOS extensions, follow these instructions here. In the application:didFinishLaunchingWithOptions:
method of your YourAppNameAppDelegate.m file, initialize the SDK:
[[Amplitude instance] initializeApiKey:@"API_KEY"];
Replace API_KEY
with the API Key given to you. You can find your project's API Key in your project's Settings page.
7. Start tracking events. Data is sent to Amplitude via events. As a result, you will have to explicitly log events in order to see any data in your project. To track an event anywhere in the app, call:
[[Amplitude instance] logEvent:@"EVENT_TYPE"];
where EVENT_TYPE
is the name you are giving to the event you want to track.
8. Event uploads. Events are saved locally. Uploads are batched to occur every 30 events and every 30 seconds as well as on app close. When a user is offline, we store their most recent 1000 events by default and then upload them once the user is online again. When the user returns online, their events are processed by first in, first out. If you want to change the frequency at which events are uploaded, you can do this by using setEventUploadThreshold
.
Tracking Events
It is important to consider what types of events you care about as a developer. You should aim to track between 20 and 200 types of events on your site. Common event types are actions the user initiates (such as pressing a button) and events you want the user to complete (such as filling out a form, completing a level, or making a payment).
Here are some resources to help you with your taxonomy or instrumentation planning:
Having a large number of distinct event types, event properties, and user properties can make data exploration and visualization very confusing. By default, we only show the first:
- 2000 distinct event types
- 2000 distinct event properties
- 1000 distinct user properties
Anything past the above thresholds will not be visualized. Note: The raw data is not impacted by this in any way, meaning that you will still see the values in the raw data but they will not be visualized in the platform. A single call to logEvent
should not have more than 1000 event properties. Likewise, a single call to setUserProperties
should not have more than 1000 user properties. If the 1000 property limit is exceeded then the properties will be dropped and a warning will be printed in the console. We have put in very conservative estimates for the event type and property caps that we do not expect to be exceeded in any practical use case. If you feel that your use case will go above those limits, please reach out to us here.
To track an event anywhere in the app, call:
[[Amplitude instance] logEvent:@"EVENT_TYPE"];
where EVENT_TYPE
is the name you are giving to the event you want to track.
Logging Events to Multiple Projects
The Amplitude iOS SDK supports logging events to multiple Amplitude projects (multiple API keys). If you want to log events to multiple Amplitude projects, you will need to use separate instances for each Amplitude project. Each new instance created will have its own apiKey
, userId
, deviceId
, and settings. You will need to assign a name to each Amplitude project/instance and use that name consistently when fetching that instance to call functions.
IMPORTANT NOTE: Once you have chosen a name for that instance you cannot change it.
Choose your instance names carefully because every instance's data and settings are tied to its name, and you will need to continue using that instance name for all future versions of your app to maintain data continuity. Note that these names do not need to correspond to the names of your projects in Amplitude, but they will need to remain consistent throughout your code. You also need to be sure that each instance is initialized with the correct apiKey
.
Instance names must be non-nil and non-empty strings, and the names are case insensitive. You can fetch each instance by name by calling:
[Amplitude instanceWithName:@"INSTANCE_NAME"]
As mentioned before, each new instance created will have its own apiKey
, userId
, deviceId
, and settings. IMPORTANT NOTE: You will have to reconfigure all the settings for each instance. For example, if you want to track session events you would have to call setTrackingSessionEvents:YES
on each instance. This gives you the freedom to have different settings for each instance.
Here is an example on how to set up and log events to two separate projects:
[[Amplitude instance] initializeApiKey:@"12345"]; // existing project, existing settings, and existing API key
[[Amplitude instanceWithName:@"new_project"] initializeApiKey:@"67890"]; // new project, new API key
[[Amplitude instanceWithName:@"new_project"] setUserId:@"joe@gmail.com"]; // need to reconfigure new project
[[Amplitude instanceWithName:@"new_project"] logEvent:@"Clicked"];
AMPIdentify *identify = [[AMPIdentify identify] add:@"karma" value:[NSNumber numberWithInt:1]];
[[Amplitude instance] identify:identify];
[[Amplitude instance] logEvent:@"Viewed Home Page"];
Synchronizing Device IDs Between Apps
As mentioned before, each new instance will have its own deviceId
. If you want your apps to share the same deviceId
, you can do so after initialization via the getDeviceId
and setDeviceId
methods. Here is an example of how to copy the existing deviceId
to the new_project
instance:
NSString *deviceId = [[Amplitude instance] getDeviceId]; // existing deviceId
[[Amplitude instanceWithName:@"new_project"] setDeviceId:deviceId]; // transferring existing deviceId to new project
Backwards Compatibility
If you were tracking users with a single app before version 3.6.0 (released March 2016), you might be wondering what will happen to existing data, existing settings, and returning users (users who already have a deviceId
and/or userId
). All of the historical data and settings are maintained on the default
instance, which is fetched without an instance name: [Amplitude instance]
. This is the way you are used to interacting with the Amplitude SDK, which means all of your existing tracking code should work as before.
Tracking Sessions
A session is a period of time that a user has the app in the foreground. In the iOS SDK, sessions are tracked automatically. Sessions within five minutes of each other are merged into a single session. When the SDK is initialized, it determines whether the app is launched into the foreground or background and it starts a new session if the app was launched in the foreground. A new session is created when the app comes back into the foreground after being out of the foreground for five minutes or more. If the app is in the background and an event is logged, then a new session is created if more than five minutes has passed since the app entered the background or when the last event was logged (whichever occurred last). Otherwise, the background event logged will be part of the current session.
You can adjust the time window for which sessions are extended by changing the variable minTimeBetweenSessionsMillis
:
[Amplitude instance].minTimeBetweenSessionsMillis = 30 * 60 * 1000; // 30 minutes
[[Amplitude instance] initializeApiKey:@"API_KEY"];
By default, '[Amplitude] Start Session' and '[Amplitude] End Session' events are no longer sent. Even though these events are not sent, sessions are still tracked by using session_id
. To re-enable those session events, add this line before initializing the SDK:
[[Amplitude instance] setTrackingSessionEvents:YES];
[[Amplitude instance] initializeApiKey:@"API_KEY"];
You can also log events as out-of-session. Out-of-session events have a session_id
of -1
and are not considered part of the current session, meaning they do not extend the current session. This might be useful if you are logging events triggered by push notifications, for example. You can log events as out-of-session by setting the input parameter outOfSession
to true
when calling logEvent
:
[[Amplitude instance] logEvent:@"EVENT_TYPE" withEventProperties:nil outOfSession:YES];
You can also log identify
events as out-of-session by setting input parameter outOfSession
to YES
when calling identify
. This is useful if you are updating user properties in the background and do not want to start a new session. Here is an example:
AMPIdentify *identify = [[AMPIdentify identify] set:@"key" value:@"value"];
[[Amplitude instance] identify:identify outOfSession:YES];
Getting the Session ID
You can use the helper method getSessionId
to get the value of the current sessionId
:
long long sessionId = [[Amplitude instance] getSessionId];
Setting Custom User IDs
If your app has its own login system that you want to track users with, you can call setUserId:
at any time:
[[Amplitude] instance] setUserId:@"USER_ID"];
You should not assign users a User ID that could change as each unique User ID is interpreted as an unique user in Amplitude. Please see our article on how we identify and count unique users for further information. You can also add the User ID as an argument to the initializeApiKey:
call:
[[Amplitude] instance] initializeApiKey:@"API_KEY" userId:@"USER_ID"];
Logging Out and Anonymous Users
A user's data will be merged on the backend so that any events up to that point from the same browser will be tracked under the same user. If a user logs out or you want to log the events under an anonymous user, you will need to:
- Set the
userId
tonil
. - Regenerate a new
deviceId
.
After doing that, events coming from the current user/device will appear as a brand new user in Amplitude. Note: If you choose to do this, you will not be able to see that the two users were using the same device. Here is an example:
[[Amplitude instance] setUserId:nil]; // not string nil
[[Amplitude instance] regenerateDeviceId];
Setting Event Properties
You can send event property attributes to any event by passing a NSDictionary object as the second argument to logEvent:withEventProperties
:
NSMutableDictionary *eventProperties = [NSMutableDictionary dictionary];
[eventProperties setValue:@"VALUE" forKey:@"KEY"];
[[Amplitude instance] logEvent:@"Compute Hash" withEventProperties:eventProperties];
Note: The keys should be of type NSString and the values should be of type NSString, NSNumber, NSArray, NSDictionary, or NSNull. You will see a warning if you try to use an unsupported type.
Arrays in Event Properties
The SDK supports arrays in event properties. Here is an example:
NSMutableArray *colors = [NSMutableArray array];
[colors addObject:@"rose"];
[colors addObject:@"gold"];
NSMutableDictionary *eventProperties = [NSMutableDictionary dictionary];
[eventProperties setObject:colors forKey:@"colors"];
[[Amplitude instance] logEvent:@"Purchase iPhone" withEventProperties:eventProperties];
Setting User Properties
IMPORTANT NOTE: Please be sure to not track any user data that may be against your privacy terms.
The SDK automatically pulls useful data about the browser, including browser type and operating system version. They are displayed as user properties in Amplitude. You can read more about them here. You can turn off this automatic tracking by disabling specific user properties using the provided AMPTrackingOptions
interface.
The SDK supports the operations set
, setOnce
, unset
, and add
on individual user properties. The operations are declared via a provided AMPIdentify
interface. Multiple operations can be chained together in a single AMPIdentify
object. The AMPIdentify
object is then passed to the Amplitude client to send to the server. The results of the operations will be visible immediately in the dashboard and will take effect for events logged after. Note: Each operation on the AMPIdentify
object returns the same instance which allows you to chain multiple operations together.
To use the AMPIdentify
interface, you will first need to include the header:
#import "AMPIdentify.h"
set
: This sets the value of a user property.AMPIdentify *identify = [[[AMPIdentify identify] set:@"gender" value:@"female"] set:@"age" value:[NSNumber numberForInt:20]]; [[Amplitude instance] identify:identify];
setOnce
: This sets the value of a user property only once. SubsequentsetOnce
operations on that user property will be ignored. In the following example, 'sign_up_date' will be set once to '2015-08-24', and the followingsetOnce
to '2015-09-14' will be ignored.AMPIdentify *identify1 = [[AMPIdentify identify] setOnce:@"sign_up_date" value:@"2015-08-24"]; [[Amplitude instance] identify:identify1]; AMPIdentify *identify2 = [[AMPIdentify identify] setOnce:@"sign_up_date" value:@"2015-09-14"]; [[Amplitude instance] identify:identify2];
unset
: This will unset and remove a user property.AMPIdentify *identify = [[[AMPIdentify identify] unset:@"gender"] unset:@"age"]; [[Amplitude instance] identify:identify];
add
: This will increment a user property by some numerical value. If the user property does not have a value set yet, it will be initialized to 0 before being incremented.AMPIdentify *identify = [[[AMPIdentify identify] add:@"karma" value:[NSNumber numberWithFloat:0.123]] add:@"friends" value:[NSNumber numberWithInt:1]]; [[Amplitude instance] identify:identify];
append
: This will append a value or values to a user property. If the user property does not have a value set yet, it will be initialized to an empty list before the new values are appended. If the user property has an existing value and it is not on a list, it will be converted into a list with the new value appended.NSMutableArray *array = [NSMutableArray array]; [array addObject:@"some_string"]; [array addObject:[NSNumber numberWithInt:56]]; AMPIdentify *identify = [[[AMPIdentify identify] append:@"ab-tests" value:@"new-user-test"] append:@"some_list" value:array]; [[Amplitude instance] identify:identify];
prepend
: This will prepend a value or values to a user property array. Prepend means inserting the value(s) at the front of a given list. If the user property does not have a value set yet, it will be initialized to an empty list before the new values are prepended. If the user property has an existing value and it is not a list, it will be converted into a list with the new value prepended.NSMutableArray *array = [NSMutableArray array]; [array addObject:@"some_string"]; [array addObject:[NSNumber numberWithInt:56]]; AMPIdentify *identify = [[[AMPIdentify identify] append:@"ab-tests" value:@"new-user-test"] prepend:@"some_list" value:array]; [[Amplitude instance] identify:identify];
Note: If a user property is used in multiple operations on the same AMPIdentify
object, then only the first operation will be saved and the rest will be ignored. In this example, only the set
operation will be saved, and the add
and unset
will be ignored:
AMPIdentify *identify = [[[[AMPIdentify identify] set:@"karma" value:[NSNumber numberWithInt:10]] add:@"friends" value:[NSNumber numberWithInt:1]] unset:@"karma"]; [[Amplitude instance] identify:identify];
Arrays in User Properties
The SDK supports arrays in user properties. Any of the user property operations above (with the exception of add
) can accept an NSArray or an NSMutableArray. You can directly set
arrays or use append
to generate an array. Here is an example:
NSMutableArray *colors = [NSMutableArray array];
[colors addObject:@"rose"];
[colors addObject:@"gold"];
NSMutableArray *numbers = [NSMutableArray array];
[numbers addObject:[NSNumber numberWithInt:4]];
[numbers addObject:[NSNumber numberWithInt:5]];
AMPIdentify *identify = [[[[AMPIdentify identify] set:@"colors" value:colors] append:@"ab-tests" value:@"campaign_a"] append:@"existing_list" value:numbers];
[[Amplitude instance] identify:identify];
Setting Multiple User Properties
You may use setUserProperties
shorthand to set multiple user properties at once. This method is simply a wrapper around AMPIdentify set
and identify
. Here is an example:
NSMutableDictionary *userProperties = [NSMutableDictionary dictionary];
[userProperties setValue:@"VALUE" forKey:@"KEY"];
[userProperties setValue:@"OTHER_VALUE" forKey:@"OTHER_KEY"];
[[Amplitude instance] setUserProperties:userProperties];
Clearing User Properties
You may use clearUserProperties
to clear all user properties at once. This will wipe all of the current user's user properties. Note: The result is irreversible! Amplitude will not be able to sync the user's user property values before the wipe to any future events that the user triggers as they will have been reset.
[[Amplitude instance] clearUserProperties];
Updating User Properties in the Background
When you are updating user properties in the background and do not wish to trigger a session while updating them, make sure to set outOfSession
to YES
:
AMPIdentify *identify = [[[AMPIdentify identify] set:@"gender" value:@"female"] set:@"age" value:[NSNumber numberForInt:20]]; [[Amplitude instance] identify:identify outOfSession:YES];
Setting Group Properties
Just like setting user properties, you can also use AMPIdentify interface to set and update group properties.
AMPIdentify *groupIdentify = [[AMPIdentify identify] set:@"members" value:[NSNumber numberForInt:80]];
[[Amplitude instance] groupIdentifyWithGroupType:@"company" groupName:@"Amplitude" groupIdentify:groupIdentify];
Tracking Revenue
The preferred method of tracking revenue for a user now is to use logRevenueV2
in conjunction with the provided AMPRevenue
interface. AMPRevenue
instances will store each revenue transaction and allow you to define several special revenue properties (such as 'revenueType', 'productIdentifier', etc.) that are used in Amplitude's Revenue Analysis and Revenue LTV charts. You can also add event properties to revenue events via the eventProperties
field. These Revenue
instance objects are then passed into logRevenueV2
to send as revenue events to Amplitude. This allows us to automatically display data relevant to revenue in the platform. You can use this to track both in-app and non-in-app purchases. Calling logRevenueV2
will generate up to 2 different event types in the platform:
- '[Amplitude] Revenue': This event is logged for all revenue events, regardless of whether or not verification is turned on.
- '[Amplitude] Revenue (Verified/Unverified)': These revenue events will contain the actual '$revenue' property.
You cannot change the default names given to these client-side revenue events in the raw data but you do have the option to modify the display name. To learn more about tracking revenue, see our documentation here.
IMPORTANT NOTE: Amplitude currently does not support currency conversion. All revenue data should be normalized to your currency of choice, before being sent to Amplitude.
To use the AMPRevenue
interface, you will first need to import the class:
#import "AMPRevenue.h"
Each time a user generates revenue, you will need to create an Revenue
object and fill out the revenue properties:
AMPRevenue *revenue = [[[AMPRevenue revenue] setProductIdentifier:@"productIdentifier"] setQuantity:3];
[revenue setPrice:[NSNumber numberWithDouble:3.99]];
[[Amplitude instance] logRevenueV2:revenue];
Each revenue event has fields available, and each field has a corresponding set
method (for example, setProductId
, setQuantity
, etc.). This table describes the different fields:
Name | Type | Description | Default |
---|---|---|---|
(optional) |
NSString |
An identifier for the product. This can be pulled from |
null |
(required) |
NSInteger |
The quantity of products purchased. Note: revenue = |
1 |
(required) |
NSNumber |
The price of the products purchased, and this can be negative. Note: revenue = |
null |
(optional) |
NSString | The type of revenue (e.g. tax, refund, income). | null |
(optional, required for revenue verification) |
NSData | This is required if you want to verify the revenue event. | null |
(optional) |
NSDictionary | A NSDictionary of event properties to include in the revenue event. | null |
Note: The price can be negative, which may be useful for tracking revenue lost (e.g. refunds or costs). You can also set event properties on the revenue event just like you would with logEvent
by passing in a NSDictionary of string key + value pairs. However, these event properties will only appear in the Event Segmentation chart and not in the revenue charts.
Revenue Verification
By default, revenue events recorded on the iOS SDK will appear in Amplitude as '[Amplitude] Revenue (Unverified)' events. To enable revenue verification, copy your iTunes Connect In-App Purchase Shared Secret into the Settings section of your project in Amplitude. You must put in a key for every single project in Amplitude where you want revenue to be verified.
After a successful purchase transaction, add the receipt data to the Revenue
object:
AMPRevenue *revenue = [[[AMPRevenue revenue] setProductIdentifier:@"productIdentifier"] setQuantity:1];
[[revenue setPrice:[NSNumber numberWithDouble:3.99]] setReceipt:receiptData];
[[Amplitude instance] logRevenueV2:revenue];
The receipt
field should be set to the receipt NSData from the app store. For details on how to obtain the receipt data, see Apple's guide on receipt validation.
IMPORTANT Note: Apple store integration is only available with iOS SDK revenue events.
Backwards Compatibility
The existing logRevenue
methods still work but are deprecated. Fields such as revenueType
will be missing from events logged with the old methods, so the ability to segment on those revenue events will be limited in the Amplitude platform.
Opting User Out of Logging
To stop all event and session logging for a user, call setOptOut
:
[[Amplitude instance] setOptOut:YES];
Logging can be restarted by calling setOptOut
again and have it set to NO
. No events will be logged during the period setOptOut
is enabled, even after it is disabled.
Disable Automatic Tracking of User Properties
By default the iOS SDK will track several user properties such as carrier and city. You can use the provided AMPTrackingOptions
interface to customize and disable individual fields. Note: Each operation on the AMPTrackingOptions
object returns the same instance which allows you to chain multiple operations together.
To use the AMPTrackingOptions
interface, you will first need to include the header:
#import "AMPTrackingOptions.h"
Before initializing the SDK with your API Key, create a AMPTrackingOptions
instance with your configuration and set it on the SDK instance:
AMPTrackingOptions *options = [[[[AMPTrackingOptions options] disableCity] disableIPAddress] disablePlatform]; [[Amplitude instance] setTrackingOptions:options];
Each field can be individually disabled and has a corresponding disable
method. This table describes the different methods:
IMPORTANT NOTE: These configurations will prevent default properties from being tracked on newly created projects, where data has not yet been sent. Please contact platform@amplitude.com if you would like default properties blocked (moving forward) on projects with existing data.
Method | Description |
---|---|
|
Disable tracking of the device's carrier. |
|
Disable tracking of the user's city. |
|
Disable tracking of the user's country. |
|
Disable tracking of the device manufacturer. |
|
Disable tracking of the device model. |
|
Disable tracking of the user's DMA. |
|
Disable tracking of the user's IDFA. |
|
Disable tracking of the user's IDFV. |
|
Disable tracking of the user's IP address. |
|
Disable tracking of the device's language. |
|
Disable tracking of the user's current latitude and longitude coordinates. |
|
Disable tracking of the device's OS name. |
|
Disable tracking of the device's OS version. |
|
Disable tracking of the device's platform. |
|
Disable tracking of the user's region. |
|
Disable tracking of the app version the user is on for your app. |
tvOS
This SDK will work with tvOS apps. To begin, follow the same setup instructions for iOS apps.
Note: tvOS apps do not have persistent storage (they only have temporary storage), so for tvOS the SDK is configured to upload events immediately as they are logged. This means eventUploadThreshold
is set to 1 by default for tvOS. It is assumed that Apple TV devices have a stable internet connection and as a result, uploading events immediately is reasonable. If you wish to revert back to the iOS batching behavior, you can do so by changing eventUploadThreshold
(this is set by default to 30 for iOS):
[[Amplitude instance] setEventUploadThreshold:30];
Swift
This SDK will work with Swift. If you are copying the source files or using CocoaPods without the use_frameworks!
directive, you should create a bridging header as documented here and add the following line to your bridging header:
#import 'Amplitude.h'
If you have use_frameworks!
set, you should not use a bridging header and instead use the following line in your Swift files:
// Before v5.0.0
import Amplitude_iOS
// After v5.0.0
import Amplitude
In either case, you can call Amplitude methods with:
Amplitude.instance().method(...)
Advanced
Setting User Groups
Note: This feature is only available to Enterprise customers who have purchased the Accounts add-on.
Amplitude supports assigning users to groups and performing queries such as Count by Distinct on those groups. An example would be if you want to group your users based on what organization they are in by using an 'orgId'. You can designate Joe to be in 'orgId' '10' while Sue is in 'orgId' '15'. When performing a query in our Event Segmentation chart, you can then select "..performed by" 'orgId' to query the number of different organizations that have performed a specific event. As long as at least one member of that group has performed the specific event, that group will be included in the count.
When setting groups, you will need to define a groupType
and groupName
(s). In the above example, 'orgId' is the groupType
and the values '10' and '15' are groupName
(s). Another example of a groupType
could be 'sport' with groupName
(s) like 'tennis' and 'baseball'. You can use setGroup
to designate which groups a user belongs to. Note: This will also set the 'groupType:groupName' as a user property. This will overwrite any existing groupName
value set for that user's groupType
as well as the corresponding user property value. groupType
is a string and groupName
can be either a string or an array of strings to indicate a user being in multiple groups (for example, if Joe is in 'orgId' '10' and '16', then the groupName
would be '[10, 16]').
You can also call setGroup
multiple times with different groupType
s to track multiple types of groups. IMPORTANT NOTE: You are allowed to track up to five different groupType
s per project. For example, let's say Sue is in 'orgId:15' and she also plays 'sport:soccer'. Now, when querying, you can count by distinct on both 'orgId' and 'sport' (although as separate queries). Any additional groupType
s after the limit will be ignored from the count by distinct user interface, but they will still be saved as user properties. Here is an example:
[[Amplitude instance] setGroup:@"orgId" groupName:[NSNumber numberWithInt:15]];
[[Amplitude instance] setGroup:@"sport" groupName:[NSArray arrayWithObjects: @"tennis", @"soccer", nil];
You can also use logEvent
with withGroups:
to set event-level groups, meaning the group destination only applies for the specific event being logged and does not persist on the user (unless you explicitly set it with setGroup
). The group input is a dictionary of groupType:groupName
pairs, where groupType
is a string and groupName
can be either a string or an array of strings. Here is an example:
NSDictionary *eventProperties = [NSDictionary dictionaryWithObjectsAndKeys: @"value", @"key", nil];
NSDictionary *groups = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:10], @"orgId", @"soccer", @"sport", nil]; [[Amplitude instance] logEvent:@"initialize_game" withEventProperties:eventProperties withGroups:groups];
Setting Date Values
Amplitude compares dates as strings, so it is recommended to use the ISO 8601 format (YYYY-MM-DDTHH:mm:ss), which will allow you to perform date comparisons in the platform (e.g. '2016-01-31' > '2016-01-01'). This will also work for datetime values (e.g. '2017-08-07T10:09:08' > '2017-08-07T01:07:00').
You can use the NSDateFormatter to format the NSDate into a string with the ISO format before setting it as a user property.
Location Tracking
If the user granted your app location permissions, then the SDK will also grab the location of the user. Amplitude will never prompt the user for location permissions and this will have to be done by your app.
Amplitude only polls for a location once on launch of the app, once on each app open, and once when the permission is first granted. There is no continuous tracking of location, although you can force Amplitude to grab the latest location by calling [[Amplitude instance] updateLocation]
. Note: This does consume more resources on the user's device, so use this wisely.
If you wish to disable location tracking done by the app, you can call [[Amplitude instance] disableLocationListening]
at any point. If you want location tracking disabled on startup of the app, call disableLocationListening
before you call initializeApiKey:
. You can always re-enable location tracking through Amplitude with [[Amplitude instance] enableLocationListening]
.
Custom Device IDs
Device IDs are set to the Identifier for Vendor (IDFV) if available, otherwise they are randomly generated. However, you can choose to instead use the Advertising Identifier (IDFA) if available by calling [[Amplitude instance] useAdvertisingIdForDeviceId]
before initializing with your API key. You can also retrieve the Device ID that Amplitude uses with [[Amplitude instance] getDeviceId]
.
If you have your own system for tracking Device IDs and would like to set a custom Device ID, you can do so with:
[[Amplitude instance] setDeviceId:@"DEVICE_ID"]
IMPORTANT NOTE: This is not recommended unless you really know what you are doing. Make sure the Device ID you set is sufficiently unique to prevent conflicts with other devices in our system. We recommend something like a UUID, and you can see [AMPUtils generateUUID]
for an example on how to generate.
As of iOS 10, if the user enables Limit Ad Tracking, then Apple will replace the IDFA with all zeros. If the iOS SDK detects an all 0 Device ID, then it will generate a random UUID and use that instead.
Automatic Reference Counting (ARC)
This code will work with both ARC and non-ARC projects. Preprocessor macros are used to determine which version of the compiler is being used.
SSL Pinning
The SDK includes support for SSL pinning. It is enabled via a preprocessor macro. If you installed the SDK using CocoaPods, you will need to enable the preprocessor macro via your Podfile by adding this post install hook:
post_install do |installer_representation|
installer_representation.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)', 'AMPLITUDE_SSL_PINNING=1']
end
end
end
If you installed the SDK directly from the source, then you can enable SSL pinning by adding the following preprocessor macro:
AMPLITUDE_SSL_PINNING=1
iOS Extensions
The SDK allows for tracking in iOS extensions. Please note that this does not include watchOS. We recommend tracking watch interactions using the partner iPhone app code or sending the data server-side via our HTTP API. To set up tracking in iOS extensions, you should follow the same setup instructions until step six. In step six, instead of initializing the SDK in application:didFinishLaunchingWithOptions:
, you should initialize the SDK in your extension's viewDidLoad
method.
Here are a couple of things to note:
- The
viewDidLoad
method will get called every time your extension is opened. This means that our SDK'sinitializeApiKey
method will get called every single time. However, this is okay since it will safely ignore subsequent calls after the first one. If you wish to, you can protect the initialization with something like adispatch_once
block. - Our definition of sessions was intended for an app use case. Depending on your expected extension use case, you might not want to enable
trackingSessionEvents
, or you may want to extend theminTimeBetweenSessionsMillis
to be longer than five minutes. You should experiment with these two settings to get your desired session definition. - In addition, you may want to decrease
eventUploadPeriodSeconds
to something shorter than 30 seconds to upload events at shorter intervals if you do not expect users to keep your extension open that long. You can also manually call[[Amplitude instance] uploadEvents];
to manually force an upload.
Here is a simple demo application showing how to instrument the iOS SDK in an extension.
Debug Logging
By default, only critical errors are logged to console. To enable debug logging, change AMPLITUDE_DEBUG
from 0
to 1
at the top of the Objective-C file you wish to examine. Error messages are printed by default. To disable error logging, change AMPLITUDE_LOG_ERRORS
from 1
to 0
in Amplitude.m.
Push Notification Events
Push notification events should not be sent client-side via the iOS SDK because a user must open the app to initialize the Amplitude SDK in order for the SDK to send the event. Therefore, if push notification events are tracked client-side then there can be data delays as the push notification event will not be sent to Amplitude's servers until the next time the user opens the app.
You can use our mobile marketing automation partners or our HTTP API to send push notification events to Amplitude.
COPPA (Children's Online Privacy Protection Act) Controls
Now you can enable or disable COPPA (Children's Online Privacy Protection Act) restrictions on IDFA, IDFV, city, IP address and location tracking.
To enable COPPA control, please call:
[[Amplitude instance] enableCoppaControl];
To disable COPPA control, please call:
[[Amplitude instance] disableCoppaControl];