Visit our new documentation site! This documentation page is no longer updated.

Treasure Data iOS SDK

You can send data from your iOS app to Treasure Data, using our iOS SDK library. In this way, you don’t have to install anything on your server-side to track the mobile app activities.

Table of Contents

GDPR compliance

To support compliance with national and global data privacy requirements such as the European General Data Privacy Regulation, our SDK provides methods that control the collection and tracking of personal data and metadata in applications and websites. When your company defines data privacy policies around personal data, you can use these methods in your code to implement default data collection behaviors, and add controls for individuals to use to manage data collection and privacy themselves.

Customers of Treasure Data must ensure that their usage of the SDK, including its use that collects personal data, complies with the legal agreement that governs access to and use of the Treasure Data service, including specifically Treasure Data's current Terms of Service (, privacy policy (, and Privacy Statement for Customer Data (


  • Basic knowledge of iOS Development (Xcode, CocoaPods)
  • iOS 5(experimental), 6, or later
  • Basic knowledge of Treasure Data

How to install iOS SDK?

Step 1: Install the Library

There are several ways to install the library.


CocoaPods is a recommended way to install Treasure Data iOS SDK. First, install CocoaPods to your PC.

$ gem install cocoapods

Add the following line to your Podfile:

pod 'TreasureData-iOS-SDK', '= 0.1.24'

If you use the SDK in Swift, add this line to your Podfile.


Finally, run pod install.

$ pod install


Download TreasureData-iOS-SDK.framework and add the .zip and the libz library into your project.

Step 2: Initialize the Library

After you’ve installed the framework, import the header file as follows:

#import <TreasureData-iOS-SDK/TreasureData.h>

Next, initialize the library in your app delegate’s application:applicationDidBecomeActive: method:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [TreasureData initializeApiEndpoint:@""];
  [TreasureData initializeWithApiKey:@"YOUR_API_KEY"];

  // This is optional, but you can encrypt the buffered data on mobile
  // devices. You can prevent people from checking the buffered events
  // on the disk.
  // [TreasureData initializeEncryptionKey:@"RANDOM_STRING_TO_ENCRYPT_DATA"];

The api key can be retrieved from the console (click here). It’s recommended to use write-only API key for SDKs. Let us know if you have any build issues.

Step 3: Send Events to the Cloud

Next, call the addEvent method at the appropriate time within your applications. The following example shows an event is sent to the table demotbl within the database testdb, when the button is clicked.

- (IBAction)clickButton:(id)sender {
  [[TreasureData sharedInstance] addEvent:@{
    @"name": @"foo bar",
    @"age": @42,
    @"comment": @"hello world"

By default, all events are buffered to the file. You need to explicitly flush the buffered data to the cloud. It won’t be uploaded automatically.

If you want to add the unique id of the device or device model information, you can use enableAutoAppendUniqId or enableAutoAppendModelInformation methods.

[[TreasureData sharedInstance] enableAutoAppendUniqId];
[[TreasureData sharedInstance] enableAutoAppendModelInformation];
[[TreasureData sharedInstance] enableAutoAppendAppInformation];
[[TreasureData sharedInstance] enableAutoAppendLocaleInformation];
[[TreasureData sharedInstance] addEvent:@{@"name":"@"foo bar"}];
// => {"td_uuid":"DA874B52-6232-4996-8228-16853109DBD9",
//     "td_os_type":"iOS",
//     "td_os_ver":"7.1.2",
//     "td_device":"iPod touch",
//     "td_model":"iPod touch",
//     "td_app_ver":"1.9.2",
//     "td_app_ver_num":"11",
//     "td_locale_country":"US",
//     "td_locale_lang":"en",
//     "name":"foo bar"
//     ... }

Also, you can append a session information to each event using Treasure Data’s class methods startSession and endSession.

[TreasureData startSession];
[[TreasureData sharedInstance] addEvent:@{@"app_event":"@"click0"}];
// => {"td_session_id":"10216937-2B47-4399-8DD5-E9E85350584B", "app_event":"click0", ... }
[TreasureData endSession];
[[TreasureData sharedInstance] addEvent:@{@"app_event":"@"click1"}];
// => {"app_event":"click1", ... }

As long as startSession is called but endSession is not called, the session will continue. Also, if startSession is called again within 10 seconds of the last calling endSession(), then the session resumes, instead of a new session being created.

The following code uploads the event when the application goes to the background, which is a fairly common pattern among our customers. You can specify the upload whenever you like. The uploader doesn’t block the main UI thread.

- (void)applicationDidEnterBackground:(UIApplication *)application
    __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;

    [[TreasureData sharedInstance] uploadEventsWithCallback:^() {
            [application endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;
        onError:^(NSString *code, NSString *msg) {
            [application endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;

When to upload and how often to upload buffered events depends on the characteristics of your application. Good times to upload include:

  • When the current screen is closing or moving to background
  • When closing the application
IP whitelist won't be applied to any import from iOS SDK. Also we've seen a lot of cases where a lot of iOS devices have an invalid timestamp (like 1970/01/01), so we're currently ignoring the log which has a timestamp older than 7 days, and newer than 3 days ahead.
If your app enables "Data Protection" and there are some other tasks that can take time and are called prior to TD iOS SDK's API such as `TreasureData#uploadEventsWithCallback` after iOS is locked, make those tasks run in background like this:
- (void)applicationWillResignActive:(UIApplication *)application
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Some tasks that can take more than 10 seconds.

Tracking Application Lifecycle Events

The SDK can be optionally enabled to automatically capture app lifecycle events (disabled by default). You must explicitly enable this option. You can set the target table through setDefaultTable:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  // TreasureData client setup...

  [[TreasureData setDefaultTable:@"app_lifecycle"];
  [[TreasureData sharedInstance] enableAppLifecycleEvent];

There are 3 kinds of events that are tracked automatically: Application Open, Install and Update. These events are captured along with relevant metadata, depending on the specific type of event:

Application Open

    "td_ios_event" = "TD_iOS_APP_OPEN";
    "td_app_ver" = "1.0";
    "td_app_ver_num" = 1;

Application Install

    "td_ios_event" = "TD_iOS_APP_INSTALL";
    "td_app_ver" = "1.0";
    "td_app_ver_num" = 1;

Application Update

    "td_ios_event" = "TD_iOS_APP_UPDATE";
    "td_app_ver" = "1.1";
    "td_app_ver_num" = 2;
    "td_app_previous_ver" = "1.0";
    "td_app_previous_ver_num" = 1;

Parameters Captured

Here is a list of parameters captured by the iOS SDK:

- td_session_id
- td_uuid : unique ID for the combination of application and device
- td_device : UIDevice.model
- td_model : UIDevice.model
- td_os_ver : UIDevice.model.systemVersion
- td_os_type : "iOS"
- td_app_ver : Core Foundation key CFBundleShortVersionString
- td_app_ver_num : Core Foundation key CFBundleVersion
- td_locale_country : [[NSLocale currentLocale] objectForKey: NSLocaleCountryCode]
- td_locale_lang : [[NSLocale currentLocale] objectForKey: NSLocaleLanguageCode]


Respecting your user’s privacy is critical to any business. Treasure Data SDK can opt-out all events tracking for a particular device and de-identify users by resetting (or disabling completely) the td_uuid. You can change the td_uuid. to a different id for all subsequent events:

[[TreasureData sharedInstance] disableCustomEvent];        // disable your own events, ones that collect through manual calls to addEvent...
[[TreasureData sharedInstance] disableAppLifecycleEvent];  // disable the auto-collected app lifecycle events

Note that unlike other option flags, enable/disableCustomEvent and enable/disableAppLifecycleEvent are persistent settings, which mean these survive across app launches. It is important to use this call whenever your users indicate that they don’t want to be tracked. It is not necessary to call the options on every Treasure Data client setup.

[[TreasureData sharedInstance] resetUniqId];
[[TreasureData sharedInstance] disableAppendUniqId];  // temporary configuration, need to call on Treasure Data client setup

resetUniqId also triggers an audit event to the defaultTable

    "td_ios_event": "forget_device_uuid",
    "td_uuid": <old_uuid>,

Advanced Tips

Retry uploading and deduplication

This SDK imports events in one manner with the following features:

  • The SDK keeps buffered events with added unique keys and retries to upload the events until confirming the events are uploaded and stored (at least once) on server side
  • The server side remembers the unique keys of all events within the past 1 hour by default and prevents duplicated imports

The deduplication window is 1 hour by default, so it’s important not to keep buffered events for more than 1 hour to avoid duplicated events.

Next Steps

For transparency, we are making our iOS SDK available as open source on Github. Check the repository to ensure that you have the most recent SDK.


3rd party Swift SDK

There is a more modern alternative SDK written in Swift

Support App Transport Security

iOS 9 or later supports App Transport Security (ATS) which enforces best practices in secure connections between an app and its back end. Our iOS SDK uses HTTPS by default not HTTP. Use of HTTPS satisfies ATS as far as not specifying the Treasure Data API endpoint with HTTP. Also, our API endpoint server satisfies ATS’s spec.

Last modified: May 18 2018 19:33:57 UTC

If this article is incorrect or outdated, or omits critical information, let us know. For all other issues, access our support channels.