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

Prerequisites

  • 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

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.17'

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

use_frameworks!

Finally, please run pod install.

$ pod install

Framework

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:@"https://in.treasuredata.com"];
  [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"
  }
  database:@"testdb"
  table:@"demotbl"];
}

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;
        }
    ];
}
Untitled-3
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.
Untitled-3
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@"https://in.treasuredata.com"];
  [TreasureData initializeWithApiKey:@"your_api_key"];

  if ([[TreasureData sharedInstance] isFirstRun]) {
    [[TreasureData sharedInstance] addEventWithCallback:@{ @"event": @"installed" }
       database:@"testdb"
          table:@"demotbl"
      onSuccess:^(){
        [[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]

Next Steps

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

Alternatives

3rd party Swift SDK

There is a more modern alternative SDK written in Swift https://github.com/recruit-lifestyle/TreasureDataSDK.

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: Sep 09 2016 06:56:54 UTC

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