Treasure Data iOS SDK

This article will help you start sending the 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


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

How to install iOS SDK?

This video demonstrates how to install iOS SDK in 5 minutes.

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, please 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, please run pod install.

$ pod install


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

Step 2: Initialize the Library

Once you’ve installed the framework, just import the header file like following:

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

Next, please 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 apikey can be retrieved from the console (click here). It’s recommended to use write-only API key for SDKs. Let us know if you’re having any build issues.

Step 3: Send Events to the Cloud

Next, please call addEvent method at the appropriate timing within your applications. This example sends the event to table demotbl within database testdb, when the button was clicked.

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

By default, all events will be bufferred to the file. You need to explicitly flush the bufferred 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 TreasureData’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 has been called but endSession hasn’t been, the session will be continued. Also, if startSession is called again within 10 seconds of the last calling endSession(), then the session will be resumed, 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 across our customers. You can do this 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;

It depends on the characteristic of your application when to upload and how often to upload buffered events. But we recommend the followings at least as good timings to upload.

  • 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, please 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.

Step 4: Track the App Installation

You can collect the first run event of your application, which can be used to track app installation event. isFirstRun and clearFirstRun methods would be useful.

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

  if ([[TreasureData sharedInstance] isFirstRun]) {
    [[TreasureData sharedInstance] addEventWithCallback:@{ @"event": @"installed" }
        [[TreasureData sharedInstance] clearFirstRun];
        [[TreasureData sharedInstance] uploadEvents];
        onError:^(NSString* errorCode, NSString* message) {
          NSLog(@"addEvent: error. errorCode=%@, message=%@", errorCode, message);
  return YES;

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]

Advanced Tips

Retry uploading and deduplication

This SDK imports events in exactly once style with the combination of these features.

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

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

Next Steps

For the transparency, we’re open sourcing our iOS SDK on Github. Please check the repository if necessary.


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 the secure connections between an app and its back end. Our iOS SDK uses HTTPS by default not HTTP. So it satisfies ATS as far as not specifying Treasure Data API endpoint with HTTP. Also, our API endpoint server satisfies ATS’s spec.

Last modified: Jul 19 2017 07:17:30 UTC

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