Working with Teak in Unity

Requesting Push Notification Permissions

In order to use push notifications on iOS, you will need to request permissions.

UnityEngine.iOS.NotificationServices.RegisterForNotifications(UnityEngine.iOS.NotificationType.Alert |
    UnityEngine.iOS.NotificationType.Badge |  UnityEngine.iOS.NotificationType.Sound);
Since:4.1.7

If you do not wish to use this method, or its Unity Replacement, you can simply call:

Teak.Instance.RegisterForNotifications();

It will be have no effect on non-iOS builds, and is safe to use on iOS 8+.

Note

We suggest that you don’t simply ask for push permissions when the app starts. We’ll be happy to talk with you to figure out what works best for your title.

Push Notifications and Local Notifications

Whenever your game is launched via a push notification, local notification, or email link Teak will let you know by sending out an event to all listeners.

You can listen for that event during by first writing a listener function, for example:

void MyOnLaunchedFromNotificationListener(TeakNotification notification)
{
    Debug.Log("OnLaunchedFromNotification: " + notification.CreativeId + " - " + notification.ScheduleId + " Incentivized? " + notification.Incentivized);
}

And then adding it to the Teak.Instance.OnLaunchedFromNotification event during Awake() in any MonoBehaviour:

void Awake()
{
    Teak.Instance.OnLaunchedFromNotification += MyOnLaunchedFromNotificationListener;
}

A TeakNotification

Incentivized:

true if the notification was incentivized, false otherwise.

ScheduleId:

The name of the schedule for the notification on the Teak Dashboard, or null if it was not a scheduled notification.

CreativeId:

The name of the notification on the Teak Dashboard.

ChannelName:

The name of the Teak ‘channel’, one of:

ios_push:iOS Push Notification
android_push:Android Push Notification
fb_a2u:Facebook App-to-User Notification
email:Email
RewardId:

Opaque reward identifier, or null if no reward.

DeepLink:

The complete deep link URL, or null if there was no deep link.

Rewards

Whenever your game should grant a reward to a user Teak will let you know by sending out an event to all listeners.

You can listen for that event during by first writing a listener function, for example:

void MyRewardListener(TeakReward reward)
{
    switch (reward.Status) {
        case TeakReward.RewardStatus.GrantReward: {
            // The user has been issued this reward by Teak
            foreach(KeyValuePair<string, object> entry in reward.Reward)
            {
                Debug.Log("[Teak Unity Cleanroom] OnReward -- Give the user " + entry.Value + " instances of " + entry.Key);
            }
        }
        break;

        case TeakReward.RewardStatus.SelfClick: {
            // The user has attempted to claim a reward from their own social post
        }
        break;

        case TeakReward.RewardStatus.AlreadyClicked: {
            // The user has already been issued this reward
        }
        break;

        case TeakReward.RewardStatus.TooManyClicks: {
            // The reward has already been claimed its maximum number of times globally
        }
        break;

        case TeakReward.RewardStatus.ExceedMaxClicksForDay: {
            // The user has already claimed their maximum number of rewards of this type for the day
        }
        break;

        case TeakReward.RewardStatus.Expired: {
            // This reward has expired and is no longer valid
        }
        break;

        case TeakReward.RewardStatus.InvalidPost: {
            // Teak does not recognize this reward id
        }
        break;
    }
}

And then adding it to the Teak.Instance.OnReward event during Awake() in any MonoBehaviour:

void Awake()
{
    Teak.Instance.OnReward += MyRewardListener;
}

A TeakReward

RewardStatus:

One of:

GrantReward:The user has been issued this reward by Teak
SelfClick:The user has attempted to claim a reward from their own social post
AlreadyClicked:The user has already been issued this reward
TooManyClicks:The reward has already been claimed its maximum number of times globally
ExceedMaxClicksForDay:
 The user has already claimed their maximum number of rewards of this type for the day
Expired:This reward has expired and is no longer valid
InvalidPost:Teak does not recognize this reward id
InternalError:Something has gone wrong, and it’s not clear what
Reward:

A dictionary containing the rewards to be granted, defined on the Teak Dashaboard.

ScheduleId:

The name of the schedule for the notification on the Teak Dashboard, or null if it was not a scheduled notification.

CreativeId:

The name of the notification or link on the Teak Dashboard.

ChannelName:

The name of the Teak ‘channel’, one of:

ios_push:iOS Push Notification
android_push:Android Push Notification
fb_a2u:Facebook App-to-User Notification
email:Email
generic_link:Reward link
Incentivized:

Will always be true.

RewardId:

Opaque reward identifier.

Working with Notifications

You can use Teak to schedule notifications for the future; delivered either to the current user, or other users.

Note

You get the full benefit of Teak’s analytics, A/B testing, and Content Management System.

Note

All notification related methods are coroutines. You may need to wrap calls to them in StartCoroutine()

Callbacks

All notification related methods are coroutines, which use a callback to communicate the results back to the caller.

The TeakNotification.Reply class has two properties:
Status:

A value that indicates success, or reason for the failure of the call:

Ok:The call was successful, and the notification has been scheduled for delivery.
UnconfiguredKey:
 The call could not be completed because Teak is unable to send a notification to the device due to a configuration setting. This can either be that the user has not granted push permissions on iOS, or that the Teak Dashboard does not have sending credentials suitable for the current device (i.e. Teak has not been provided with an FCM Sender ID/API Key, APNS certificate, or ADM Client ID/Client Secret).
InvalidDevice:The call could not be completed because Teak is not aware of the device scheduling the notification. This can happen if Teak was completely unable to get a push token for the device, which can occur due to intermittent failures in APNS/FCM/ADM, intermittent networking failures between the device and those services, or system modifications made on rooted devices.
InternalError:An unknown error occured, and the call should be retried.
Notifications:

If the call was successful, a List containing the notification schedule ids that were created or canceled by the call.

Scheduling a Local Notification

To schedule a notification from your game, use:

IEnumerator TeakNotification.ScheduleNotification(string scheduleName, string defaultMessage,
    long delayInSeconds, System.Action<TeakNotification.Reply> callback)

Important

All notification related methods are coroutines. Unless you want the method to block execution, you must use StartCoroutine

Parameters
scheduleName:A value used to identify the message creative in the Teak CMS e.g. “daily_bonus”
defaultMessage:The text to use in the notification if there are no modifications in the Teak CMS.
delayInSeconds:The number of seconds from the current time before the notification should be sent.
callback:The callback to be called after the notification is scheduled

Note

The maximum delay for a Local Notification is 30 days.

Scheduling a Long-Distance Notification

To schedule a notification from your game, delivered to a different user of your game use:

IEnumerator TeakNotification.ScheduleNotification(string scheduleName, long delayInSeconds,
    string[] userIds, System.Action<TeakNotification.Reply> callback)

Important

All notification related methods are coroutines. Unless you want the method to block execution, you must use StartCoroutine

Parameters
scheduleName:A value used to identify the message creative in the Teak CMS e.g. “daily_bonus”
delayInSeconds:The number of seconds from the current time before the notification should be sent.
userIds:An array of user ids to which the notification should be delivered
callback:The callback to be called after the notifications are scheduled

Note

The maximum delay for a Long-Distance Notification is 30 days.

Canceling a Notification

To cancel a previously scheduled notification, use:

IEnumerator TeakNotification.CancelScheduledNotification(string scheduledId,
    System.Action<TeakNotification.Reply> callback)

Important

All notification related methods are coroutines. Unless you want the method to block execution, you must use StartCoroutine

Parameters
scheduleId:Passing the id received from ScheduleNotification() will cancel that specific notification; passing the scheduleName used to schedule the notification will cancel all scheduled notifications with that creative id for the user
callback:The callback to be called after the notification is canceled

Canceling all Local Notifications

To cancel all previously scheduled local notifications, use:

IEnumerator TeakNotification.CancelAllScheduledNotifications(
    System.Action<TeakNotification.Reply> callback)

Important

All notification related methods are coroutines. Unless you want the method to block execution, you must use StartCoroutine

Parameters
callback:The callback to be called after the notifications are canceled

Note

This call is processed asynchronously. If you immediately call TeakNotification.ScheduleNotification() after calling TeakNotification.CancelAllScheduledNotifications() it is possible for your newly scheduled notification to also be canceled. We recommend waiting until the callback has fired before scheduling any new notifications.

Determining if User Has Disabled Push Notifications

You can use Teak to get the state of push notifications for your app.

If notifications are disabled, you can prompt them to re-enable them on the settings page for the app, and use Teak to go directly the settings for your app.

Notification State

To get the state of push notifications, use:

NotificationState PushNotificationState
Return
UnableToDetermine:
 Unable to determine the notification state.
Enabled:Notifications are enabled, your app can send push notifications.
Disabled:Notifications are disabled, your app cannot send push notifications.
Provisional:Provisional notifications are enabled, your app can send notifications but they will only display in the Notification Center (iOS 12+ only).
NotRequested:The user has not been asked to authorize push notifications (iOS only).

Example:

if (Teak.Instance.PushNotificationState == Teak.NotificationState.Disabled) {
    // Show a button that will let users open the settings
}

Opening the Settings for Your App

If you want to show the settings for your app, use:

bool OpenSettingsAppToThisAppsSettings()

This function will return false if Teak was not able to open the settings, true otherwise.

Example:

// ...
// When a user presses a button indicating they want to change their notification settings
Teak.Instance.OpenSettingsAppToThisAppsSettings()

Post Launch Summary

Each time your game launches, Teak will pass all of the information it has on the launch to you via the OnPostLaunchSummary event.

LaunchLink:

The URL used to launch the game, or null.

ScheduleName:

If launched via a Teak channel, the name of the schedule on the Teak dashboard which was responsible, or null.

ScheduleId:

If launched via a Teak channel, the id of the schedule on the Teak dashboard which was responsible, or null.

CreativeName:

If launched via a Teak channel, the name of the creative on the Teak dashboard which was responsible, or null.

CreativeId:

If launched via a Teak channel, the id of the creative on the Teak dashboard which was responsible, or null.

RewardId:

If a Teak reward was attached, the id of that reward, or null.

ChannelName:

If launched via a Teak channel, null, or one of:

ios_push:iOS Push Notification
android_push:Android Push Notification
fb_a2u:Facebook App-to-User Notification
email:Email
generic_link:Reward link
DeepLink:

The deep link, or null.

SourceSendId:

If launched via a Teak push notification or email, the id of that push or email, or null.

Player Properties

Teak can store up to 16 numeric, and 16 string properties per player. These properties can then be used for targeting.

You do not need to register the property in the Teak Dashboard prior to sending them from your game, however you will need to register them in the Teak Dashboard before using them in targeting.

Numeric Property

To set a numeric property, use:

void SetNumericAttribute(string key, double value)

Example:

Teak.Instance.SetNumericAttribute("coins", new_coin_balance);

String Property

To set a string property, use:

void SetStringAttribute(string key, string value)

Example:

Teak.Instance.SetStringAttribute("last_slot", "amazing_slot_name");

Analytics Events

Teak can be used to track analytics events which can then be used for targeting. These events are automatically batched by the Teak SDK, you do not need to perform your own batching.

Event Format

Teak events are a tuple of values, ‘action’, ‘object type’ and ‘object instance’. For example: [‘LevelUp’, ‘Fishing’, ‘13’].

Object instance, and object type are optional, but if you provide an object instance, you must also provide an object type, for example [‘FishCaught’, null, ‘13’] is not allowed, but [‘FishCaught’, ‘Salmon’] is allowed.

Tracking an Event

To track that an event occurred, use:

void TrackEvent(string actionId, string objectTypeId, string objectInstanceId)

Example:

Teak.Instance.TrackEvent("LevelUp", "Fishing", "13");

Incrementing Events

Incremented events are used for analytics which grow over time. You cannot provide negative values.

To increment an event, use:

void IncrementEvent(string actionId, string objectTypeId, string objectInstanceId, ulong count)

Examples:

Teak.Instance.IncrementEvent("coin_sink", "slot", "Happy Land Slots", 25000);
Teak.Instance.IncrementEvent("spin", "slot", "Happy Land Slots", 1);
// <after the spin happens>
Teak.Instance.IncrementEvent("coin_source", "slot", "Happy Land Slots", 1000000);

Logout

You can log out the current user using Logout. If the user is logged out, Teak will not process deep links or rewards until a user is logged in, via IdentifyUser.

Reporting Facebook Payments Purchases

If you need to report purchases on Facebook Canvas from using any of the FB.Canvas.Pay methods, use:

void ReportCanvasPurchase(string rawResult)

For example:

FB.Canvas.PayWithProductId(
    this.testPurchaseSku,
    "purchaseiap",
    null,
    null,
    (IPayResult result) => {
        if(!string.IsNullOrEmpty(result.Error)) {
            Debug.LogError(result.Error);
        } else {
            Teak.Instance.ReportCanvasPurchase(result.RawResult);
        }
    }
);
Parameters
rawResult:The value of IPayResult.RawResult

Preprocessor Defines

Teak sets some preprocessor defines for your use in Teak/Editor/TeakPreProcessDefiner.cs.

TEAK_2_0_OR_NEWER:
 The Teak SDK version is at least 2.0
TEAK_2_1_OR_NEWER:
 The Teak SDK version is at least 2.1
TEAK_2_2_OR_NEWER:
 The Teak SDK version is at least 2.2
TEAK_2_3_OR_NEWER:
 The Teak SDK version is at least 2.3
TEAK_3_0_OR_NEWER:
 The Teak SDK version is at least 3.0
TEAK_3_1_OR_NEWER:
 The Teak SDK version is at least 3.1
TEAK_3_2_OR_NEWER:
 The Teak SDK version is at least 3.2
TEAK_3_3_OR_NEWER:
 The Teak SDK version is at least 3.3
TEAK_3_4_OR_NEWER:
 The Teak SDK version is at least 3.4
TEAK_4_0_OR_NEWER:
 The Teak SDK version is at least 4.0
TEAK_4_1_OR_NEWER:
 The Teak SDK version is at least 4.1