# Cordova Plugin for TD Android and iOS Sdks

The Cordova Plugin enables tracking of events on Ionic app platforms using TD Android and iOS mobile SDKs. td-cordova-sdk is a module that uses native iOS and Android SDKs underneath to provide a bridge between Treasure Data and Cordova apps.

You can see more detailed documentation in the GitHub repositories for [td-android-sdk](https://github.com/treasure-data/td-android-sdk) and [td-ios-sdk](https://github.com/treasure-data/td-ios-sdk).

Treasure Data recommends you verify the implementation of any new features or functionality at your site using the Treasure Data JavaScript SDK version 3 before you start using it in production. It manages cookies differently. Be aware when referring to most of these articles that you need to define the suggested event collectors and Treasure Data JavaScript SDK version 3 calls in your solutions.For example, change //cdn.treasuredata.com/sdk/2.5/td.min.js to //cdn.treasuredata.com/sdk/3.0.0/td.min.js.

* [Installing the Plugin](#installing-the-plugin)
* [Using the Plugin Methods](#using-the-plugin-methods)
* [Configuring the Plugin](#configuring-the-plugin)
* [Add an Event to Local Buffer](#add-an-event-to-local-buffer)
* [Upload Buffered Events to TreasureData](#upload-buffered-events-to-treasuredata)
* [Add and Upload Custom Events](#add-and-upload-custom-events)
* [Track App Lifecycle Events Automatically (Android only)](#track-app-lifecycle-events-automatically-android-only)
* [Track In-App Purchase Events Automatically](#track-in-app-purchase-events-automatically)
* [Add the UUID of the Device to Each Event Automatically](#add-the-uuid-of-the-device-to-each-event-automatically)
* [Add a UUID to Each Event Record Automatically](#add-a-uuid-to-each-event-record-automatically)
* [Add the Advertising Id to Each Event Record Automatically](#add-the-advertising-id-to-each-event-record-automatically)
* [Add the Device Model Information to Each Event Automatically](#add-the-device-model-information-to-each-event-automatically)
* [Add Application Package Version Information to Each Event Automatically](#add-application-package-version-information-to-each-event-automatically)
* [Add Locale Configuration Information to Each Event Automatically](#add-locale-configuration-information-to-each-event-automatically)
* [Use Server Side Upload Timestamp](#use-server-side-upload-timestamp)
* [Start/End Tracking a Session](#startend-tracking-a-session)
* [Profile API](#profile-api)
* [Enable and Disable Debug Log](#enable-and-disable-debug-log)
* [Enable and Disable Retry Uploading](#enable-and-disable-retry-uploading)
* [Device and OS support](#device-and-os-support)


## Installing the Plugin

Install the Cordova plugin using the following code.

```bash
cordova plugin add td-cordova-sdk
```

## Using the Plugin Methods

After installing the plugin, you can access the methods through the `cordova.plugins.TreasureDataPlugin` namespace.

## Configuring the Plugin

Edit the following **fields** with the correct information.

```javascript
    TreasureDataPlugin.setup({
      apiEndpoint: '<https://in.treasure-data.com',> // Or other supported endpoints
      encryptionKey: '<xxxxx>',
      apiKey: '<xxxxx>', /// You should use write only api key
      defaultDatabase: '<default_database>',
      defaultTable: '<default_table_name>',
      cdpEndpoint: '<https://cdp.in.treasuredata.com'> // Or other cdp endpoints
    })
```

## Add an Event to Local Buffer

You can add custom events to a specific database and table as shown in the following example. Specify the database and table to which you want to import the events. The total length of database and table names must be shorter than 129 characters.

```javascript
const customEvent = {event: 'Custom event', data: new Date().getSeconds()};
TreasureDataPlugin.addEvent(customEvent, 'table', 'database');
// or
TreasureDataPlugin.addEvent(customEvent, 'table');
```

If the database parameter is not specified, the `defaultDatabase` configuration in `TreasureDataPlugin.setup({...})` is used instead.

Optionally, if you need to know when `addEvent` is successful or failed, use `addEventWithCallback` instead. You can pass `null` or `undefined` as the database parameter and the `defaultDatabase` configuration in `TreasureDataPlugin.setup({...})` is used instead.

```javascript
const customEvent = {
    event: 'Custom event',
    data: new Date().getSeconds()
};
TreasureDataPlugin.addEventWithCallback(customEvent, 'table', 'database', () => {
    console.log('Add Event Successfully');
}, (errorCode, errorMessage) => {
    console.log('Add Event Failed', errorCode, errorMessage);
});
```

## Upload Buffered Events to TreasureData

You can upload all buffered events to Treasure Data at any time with the `uploadEvent` function.

```javascript
TreasureDataPlugin.uploadEvents();
```

Optionally, if you need to know when `uploadEvents` is successful or failed, use `uploadEventsWithCallback` instead.

```javascript
    TreasureDataPlugin.uploadEventsWithCallback(() => {
      console.log('Upload events successfully')
    }, (errorCode, errorMessage) => {
      console.log('Failed to upload events', errorCode, errorMessage);
    });
```

## Add and Upload Custom Events

Adding and uploading custom events are enabled by default. You can disable and enable this feature at any time.

To disable custom events:

```javascript
TreasureDataPlugin.disableCustomEvent();
```

To enable custom events:

```javascript
TreasureDataPlugin.enableCustomEvent();
```

## Track App Lifecycle Events Automatically (Android only)

This feature is only available on Android. App lifecycle event tracking is optional and not enabled by default. You can track app lifecycle events automatically using:

```javascript
TreasureDataPlugin.enableAppLifecycleEvent();
```

```javascript
TreasureDataPlugin.disableAppLifecycleEvent();
```

To check if tracking app lifecycle events is enabled:

```javascript
TreasureDataPlugin.isAppLifecycleEventEnabled((enabled) => {
    console.log('Tracking app lifecycle event is enabled?', enabled ? 'yes' : 'no');
})
```

## Track In-App Purchase Events Automatically

You don't need to check for the platform when calling this feature's APIs, they will simply be a no-op.
In-app purchase event tracking is optional and not enabled by default.

To track in-app purchase events automatically:

```javascript
TreasureDataPlugin.enableInAppPurchaseEvent();
```

To disable tracking in-app purchase events:

```
TreasureDataPlugin.disableInAppPurchaseEvent();
```

To check if tracking in-app purchase events is enabled:

```javascript
TreasureDataPlugin.isInAppPurchaseEventEnabled((enabled) => {
  console.log('Tracking in app purchase event is enabled?', enabled ? 'yes' : 'no');
})
```

## Add the UUID of the Device to Each Event Automatically

The UUID of the device will be added to each event automatically with the following call. This value won't change until the application is uninstalled.

```javascript
TreasureDataPlugin.enableAutoAppendUniqId();
```

To disable adding the UUID of the device to each event automatically:

```javascript
TreasureDataPlugin.disableAutoAppendUniqId();
```

To reset the UUID of the device

```javascript
TreasureDataPlugin.resetUniqId();
```

## Add a UUID to Each Event Record Automatically

A UUID will be added to each event record automatically with the following call. Each event has a different UUID.

```javascript
    TreasureDataPlugin.enableAutoAppendRecordUUID();
```

To disable adding the UUID to each event record automatically:

```javascript
TreasureDataPlugin.disableAutoAppendRecordUUID();
```

## Add the Advertising Id to Each Event Record Automatically

Advertising Id will be added to each event record automatically with the following call.

```javascript
TreasureDataPlugin.enableAutoAppendAdvertisingIdentifier();
// Or specify custom column
TreasureDataPlugin.enableAutoAppendAdvertisingIdentifier('custom_aaid_column');
```

In **Android** , you must install Google Play Service Ads (Gradle `com.google.android.gms:play-services-ads`) as a dependency for this feature to work.In **iOS** , you must link the Ad Support framework in the Link Binary With Libraries build phase for this feature to work.

If a User turns on the Limit Ad Tracking feature in their device, Treasure Data will not add the Advertising Id to the record.

Due to the asynchronous nature of getting the Advertising Id, after enabling adding the advertising ID to each record, it may take some time for the Advertising Id to be available to be added to the record. However, Treasure Data does cache the Advertising Id to add to the next event without having to wait for the fetch Advertising Id task to complete.

To disable adding Advertising Id:

```javascript
TreasureDataPlugin.disableAutoAppendAdvertisingIdentifier();
```

## Add the Device Model Information to Each Event Automatically

To add device model information to each event automatically:

```javascript
TreasureDataPlugin.enableAutoAppendModelInformation();
```

To disable adding device model information:

```javascript
TreasureDataPlugin.disableAutoAppendModelInformation();
```

## Add Application Package Version Information to Each Event Automatically

To enable adding application version information to each event automatically:

```javascript
TreasureDataPlugin.enableAutoAppendAppInformation();
```

To disable adding application version information to each event automatically:

```javascript
TreasureDataPlugin.disableAutoAppendAppInformation();
```

## Add Locale Configuration Information to Each Event Automatically

To enable adding locale configuration information to each event automatically:

```javascript
TreasureDataPlugin.enableAutoAppendLocaleInformation();
```

To disable adding locale configuration information to each event automatically:

```javascript
TreasureDataPlugin.disableAutoAppendLocaleInformation();
```

## Use Server Side Upload Timestamp

If you want to enable recording the server side upload timestamp in addition to the client device time that is recorded when your application calls addEvent, use the following:

```javascript
TreasureDataPlugin.enableServerSideUploadTimestamp();
// Or specify custom column
TreasureDataPlugin.enableServerSideUploadTimestamp('custom_server_side_upload_timestamp_column');
```

To disable recording the server side upload timestamp:

```javascript
TreasureDataPlugin.disableServerSideUploadTimestamp();
```

## Start/End Tracking a Session

The Cordova plugin exposes instance sessions: `startSession` and `endSession` record `td_session_event` start and end events in the table you specify, and events tracked in between carry `td_session_id`. See [Tracking Sessions with Mobile SDKs](/products/customer-data-platform/integration-hub/streaming/mobile/tracking-sessions-with-mobile-sdks) for session semantics.

To start tracking a session:

```javascript
TreasureDataPlugin.startSession(sessionTable, sessionDatabase);
```

To end tracking the current session:

```javascript
TreasureDataPlugin.endSession(sessionTable, sessionDatabase);
```

## Profile API

This feature is not enabled on accounts by default.

You must set the cdpEndpoint as property of TreasureData's sharedInstance as shown in this example:

```javascript
    var plugin = cordova.plugins.TreasureDataPlugin;
    function success(response) {
      /* response format => [
        {
          "segments": ["segment_id"],
          "attributes": {
            "age": ##,
            "td_client_id": "xxxxxxxxxxxxx"
          },
          "audienceId": "audience_id",
          "key": { "name": "user_id", "value": "xxxxxxx" }
        },
        {
          "segments": ["segment_id", "segment_id"],
          "attributes": {
            "im_segments": "xxxxxxxxxxxx",
            "work_style_per_family": "xxxxxxxx"
          },
          "audienceId": "audience_id",
          "key": {
            "name": "td_client_id",
            "value": "xxxxxxxxxxxxx"
          }
        }
      ] */
    
      // yay
    }
    
    function error() {
      // nay
    }
    
    plugin.fetchUserSegments(
      ["audience_id","audience_id"],
      {
        user_id: "xxxxx",
        td_client_id: "xxxxx"
      },
      success,
      error
    );
```

## Enable and Disable Debug Log

To enable the debug log:

```javascript
TreasureDataPlugin.enableLogging();
```

To disable the debug log:

```javascript
TreasureDataPlugin.disableLogging();
```

## Enable and Disable Retry Uploading

To enable retry uploading:

```javascript
TreasureDataPlugin.enableRetryUploading();
```

To disable retry uploading:

```javascript
TreasureDataPlugin.disableRetryUploading();
```

# Device and OS support

See the native SDKs repository for more information about supported devices and OS.