SDK Integration

Installing the Appboy SDK will provide you with the ability to collect analytics and engage users with push notifications and native in-app messages.

Before you can start using Appboy in your Unity scripts, you’ll need to import the plugin files to your Unity project.

Note: As of Appboy Unity SDK v1.5.0, Appboy’s Unity plugins require Unity 5. See the CHANGELOG for more information.

Initial SDK Setup

Follow the below instructions to get Appboy running in your Unity application. If you are transitioning from a manual integration, please read the instructions on Transitioning From a Manual to an Automated Integration.

Time Estimate: 5 Minutes

Step 1: Importing the Appboy Unity Package

As of SDK v.1.8.0, the native Unity functionality, iOS libraries and Android libraries for Appboy’s Unity plugin are bundled as a Unity package.

  1. To import the provided Appboy Unity package into your project, download the package associated with the most recent SDK release. There are two options:
    • Appboy.unitypackage
      • This package bundles the Appboy Android and iOS SDKs as well as the SDWebImage dependency for the iOS SDK, which is required for proper functionality of Appboy’s In-App Messaging and News Feed features. The SDWebImage framework is used for downloading and displaying images, including GIFs. If you intend on utilizing full Appboy functionality, download and import this package.
    • Appboy-nodeps.unitypackage
      • This package only bundles the Appboy Android and iOS SDKs and the accompanying C# interface, which provides native Unity functionality for Appboy’s iOS plugin.
  2. In the Unity Editor, import the package into your Unity project by navigating to Assets > Import Package > Custom Package.
  3. (Optional) Deselect any files you do not wish to import. Note that the Appboy and iOS subdirectories are required for this integration.
  4. Click “Import”.

Alternatively, Appboy also provides the option of customizing and exporting the Unity package.

Step 2: Setting Your API Key

As of SDK v.1.8.0, Appboy provides a native Unity solution for automating the Unity iOS integration. This solution modifies the built Xcode project using Unity’s PostProcessBuildAttribute and subclasses the UnityAppController using the IMPL_APP_CONTROLLER_SUBCLASS macro.

  1. In the Unity Editor, open the Appboy Configuration Settings by navigating to Appboy > Appboy Configuration.
  2. Check the “Automate Unity iOS Integration” box.
  3. In the “Appboy API Key” field, input your application’s API key from the Appboy Dashboard. Your Appboy Configuration settings should look like this: Appboy Config Editor

Note: If your application is already using another UnityAppController subclass, you will need to merge your subclass implementation with AppboyAppDelegate.mm.

Step 3: SDK Integration Complete

Appboy should now be collecting data from your application and your basic integration should be complete. Continue on to the following sections to integrate in-app messages, the News Feed, push notifications and the complete suite of Appboy features.

In-App Message Integration

By default, Appboy will handle and display in-app messages via the native iOS SDK. If you wish to pass in-app messages to Unity or customize in-app message display and handling, you must set an in-app message listener by doing the following:

  1. Please ensure that you have followed the Initial SDK Setup steps on setting your Appboy API key through Unity.
  2. Set the name of your Game Object and In-App Message listener callback method under “Set In-App Message Listener.”
  3. If you set a listener, Appboy will send the in-app message to Unity instead of displaying it, and your in-app message will not automatically appear in your app. If you check “Appboy Displays In-App Messages”, Appboy will both send the in-app message to your callback method and display it.

    In-App Message Listener

Implementation Example

For a sample implementation, take a look at the InAppMessageReceivedCallback in AppboyBindingTester.cs.

In-App Message Integration Complete

Your Unity application is now set up to receive in-app messages from Appboy. See the In-App Message documentation for information on in-app message customization.

News Feed Integration

Appboy’s News Feed allows you to insert permanent content directly into your app from our web dashboard. Appboy does not provide a default UI for the News Feed in Unity. Instead, the Appboy SDK passes along all News Feed cards to Unity. If you wish to integrate the News Feed into your application, you must do the following:

  1. Ensure that you have followed the Initial SDK Setup steps on setting your Appboy API key through Unity.
  2. Set the name of your Game Object and News Feed listener callback method under “Set News Feed Listener.”

    Set News Feed Listener

Implementation Example

For a sample implementation, take a look at the FeedReceivedCallback in AppboyBindingTester.cs.

News Feed Integration Complete

Your Unity application is now set up to receive the News Feed data model from Appboy. Next, see the News Feed documentation for information on requesting a News Feed data refresh and logging News Feed analytics.

Transitioning from Manual to Automated Integration

To take advantage of the automated iOS integration offered in Unity SDK v.1.8.0, follow these steps on transitioning from a manual to an automated integration.

If the only modifications you have made to your app’s built Xcode project have been for the Appboy integration, you can follow the instructions on replacing your Xcode project. Otherwise, follow the instructions for appending to your Xcode project.

Replace Xcode Project

  1. Follow the integration instructions on importing the Appboy Unity package and setting your API key through Unity.
  2. Based on the features of your previous Appboy integration, continue on to the instructions for integrating push notifications, setting in-app message listeners, and setting feed listeners.
  3. Export your project from Unity to the same destination and choose “Replace.”

Append to Xcode Project

  1. Remove all Appboy-related code from your Xcode project’s UnityAppController.mm.
  2. Remove Appboy’s iOS libraries from your Unity or Xcode project (i.e., AppboyKit and SDWebImage) and import the Appboy Unity package into your Unity project.
  3. Follow the integration instructions on setting your API key through Unity.
  4. Based on the features of your previous Appboy integration, continue on to the instructions for integrating push notifications, setting in-app message listeners, and setting feed listeners.
  5. Export your project from Unity to the same destination and choose “Append.”

Manual SDK Integration

Initial SDK Setup

Follow the instructions below to manually integrate Appboy into your built Xcode project.

Time Estimate: 20-30 Minutes

Step 1: Cloning the Unity SDK

Clone the Appboy Unity SDK Github project

git clone git@github.com:Appboy/appboy-unity-sdk.git

Step 2: Copying Required Plugins

Are you using other plugins? What to Copy Where to Copy
NO the Plugins directory from the Unity SDK the Assets folder of your Unity Project
YES Plugins/Appboy/AppboyBinding.cs /<your-project>/Assets/Plugins
YES Plugins/iOS /<your-project>/Assets/Plugins/iOS

Step 3: Generating Xcode project & Adding Required Classes

Now that you’ve copied over the requisite plugins, the following steps will help you generate your Xcode project and add the required classes for the Appboy SDK to function:

  1. Generate your Xcode project in Unity by clicking on File > Build Settings…
  2. Select iOS as the platform and click “Build”.
  3. Select /your-project/your-iOS-project/ as the build location.
  4. Confirm that Unity has copied the files AppboyBinding.m, AppboyUnityManager.h, and AppboyUnityManager.mm to your generated project under the “Libraries” directory.
    • If these three files were not automatically integrated into your project or linked correctly by Unity, you will need to manually copy them into the “Classes” directory of your generated project (without checking “Copy items if needed” in the Options). Then, in the Compile Sources step of your target’s Build Phases tab, make sure to delete any incorrect paths.

Step 4: Integrating the Appboy iOS SDK

You must now integrate the standard Appboy iOS SDK into your project.

  1. Add the AppboyKit SDK and SDWebImage.framework to your project.
    1. In Xcode, from the project navigator, select the destination project or group for Appboy
    2. Navigate to File > Add Files to “Project_Name”
    3. Add the AppboyKit folder and SDWebImage.framework to your project as a group from the Unity SDK Libraries Folder.
      • If you are integrating for the first time, make sure to expand “Options” and check “Copy items if needed”
      • Check “Create groups” option for the “Added folders” Add libraries
  2. Add Required iOS Libraries
    1. Click on the target for your project (using the left-side navigation), and select the “Build Phases” tab
    2. Click the + button under “Link Binary With Libraries”
    3. In the menu, select SystemConfiguration.framework and press the Add button. Add SystemConfiguration.framework
    4. Mark this library as “Required” using the pull-down menu next to SystemConfiguration.framework Mark SystemConfiguration.framework as Required
    5. Repeat Steps 3 and 4 to add each of the following required frameworks to your project, marking each as “Required”
      • QuartzCore.framework
      • CoreImage.framework
      • libz.tbd Rinse and Repeat
    6. Add the following frameworks and mark them as “Optional”:
      • CoreTelephony.framework
      • ImageIO.framework
      • Accounts.framework
      • AdSupport.framework
      • StoreKit.framework
      • CoreLocation.framework
        • You must authorize location for your users using CLLocationManager in your app
  3. Configure the Appboy Library and Framework
    1. In the “Build Phases” panel, expand the “Link Binary With Libraries” section and the “Copy Bundle Resources” section
    2. Your “Build Phases” panel should look like the following screenshot:
      • Please ensure that libAppboyKitLibrary.a is within the “Link Binary With Libraries” section, and Appboy.bundle is within the “Copy Bundle Resources” section. Link iOS Binary and Library

Step 5: Updating the Project Build Settings

  1. Click on the target for your project (using the left-side navigation), and select the “Build Settings” tab
  2. Find “Other Linker Flags” and add -ObjC to the row Adding `-ObjC` in "Other Linker Flags"
  3. Find “Framework Search Paths” and add the relative path of the SDWebImage.framework. In the sample here, the relative path is ./../../../Libraries Adding the Path to SDWebImage.framework to "Framework Search Paths"

Step 5: Modifying UnityAppController.mm

You now must make modifications to your generated Classes/UnityAppController.mm:

  1. At the top of UnityAppController.mm add the following import statements:
	#import "AppboyKit.h"
	#import "AppboyUnityManager.h"
  1. In the method applicationDidFinishLaunchingWithOptions, add the following code snippet above the return statement. Note: Be sure to replace "YOUR-API-KEY" with the Appboy API key from the Appboy dashboard.
	[Appboy startWithApiKey:@"YOUR-API-KEY"
    	    inApplication:application
        	withLaunchOptions:launchOptions];

Step 6: Updating Your App From Unity

Finally, if you need to update your app from Unity, ensure that you choose the same location to generate the Xcode project each time and choose “Append” the existing folder when prompted by Unity to ensure that you don’t have to redo any of your Appboy setup in the future. (Note that Unity may overwrite the Framework Search Paths even when appending to the Xcode project.)

Step 7: SDK Integration Complete

Appboy should now be collecting data from your application and your basic integration should be complete. Continue on to the following sections to integrate in-app messages, the News Feed, push notifications and the complete suite of Appboy features.

In-App Message Integration

You can set an in-app message listener by manually modifying your built Xcode project. In order to pass in-app messages from Appboy to Unity, you must add the following code to your applicationDidFinishLaunchingWithOptions method within your UnityAppController.mm file:

[Appboy sharedInstance].inAppMessageController.delegate = [AppboyUnityManager sharedInstance];

[[AppboyUnityManager sharedInstance] addInAppMessageListenerWithObjectName:@"Your Unity Game Object Name" callbackMethodName:@"Your Unity Call Back Method Name"];
  • @"Your Unity Game Object Name" must be replaced with the Unity object name you want to listen to the in-app message.
  • @"Your Unity Call Back Method Name" is the call back method name that handles the in-app message.
  • The call back method must be contained within the Unity object you passed in as the first parameter.

Note: If you have added an in-app message listener, Appboy will send the message to Unity instead of displaying it by default, meaning your in-app message will not automatically appear in your app. To have Appboy handle displaying in-app messages, change the (BOOL) onInAppMessageReceived:(ABKInAppMessage *)inAppMessage method in AppboyUnityManager.mm and make it return NO.

News Feed Integration

You can set a feed listener by manually modifying your built Xcode project. In order to pass the News Feed from Appboy to Unity, you must add the following code to your applicationDidFinishLaunchingWithOptions method within your UnityAppController.mm file:

[[AppboyUnityManager sharedInstance] addFeedListenerWithObjectName:@"Your Unity Game Object Name" callbackMethodName:@"Your Unity Call Back Method Name"];
  • @"Your Unity Game Object Name" must be replaced with the Unity object name you want to receive the News Feed.
  • @"Your Unity Call Back Method Name" is the call back method name that handles the News Feed model.
  • The call back method must be contained within the Unity object you passed in as the first parameter.

Push Notifications

A push notification is an out-of-app alert that appears on the user’s screen when an important update occurs. Push notifications are a valuable way to provide your users with time-sensitive and relevant content or to re-engage them with your app.

Sample push notification:

Sample Push

Check out Appboy Academy for additional best practices.

Time Estimate: 7 Minutes

Step 1: Configure the Apple Developer Settings

  1. Navigate to the iOS Provisioning Portal
  2. Select Identifiers > App IDs in the left sidebar

    iOSPush3

  3. Select your application
  4. If push notifications are not enabled, click Edit to update the app settings AppleProvisioningOptions
  5. Tick the Enable check box and click Create Certificate under the Production SSL Certificate iOSPush3
  6. Follow the instructions from the SSL certificate assistant. You should now see a green status to indicate that push is enabled. Note: You must update your provisioning profile for the app after you create your SSL certificates. A simple “Refresh” in the organizer will accomplish this.

Step 2: Export Your Push Certificate

  1. Download the production push certificate that you just created and open it with the Keychain Access application
  2. In Keychain Access, click on My Certificates and locate your push certificate private key
  3. Export it as a .p12 file and use a temporary, unsecure password (you will need this password when uploading your certificate to Appboy)
  4. Navigate to the App Settings page in the dashboard and upload your production certificate. push upload example Note: You can upload either your development or universal push certificates to the dashboard for your distribution provisioning profile apps, but you can only have one active at a time. As such, if you wish to do repeated testing of push notifications once your app goes live in the App Store, we recommend setting up a separate App Group or App for the development version of your app.

Step 3: Customize Push Notification Settings

As of SDK v.1.8.0, Appboy provides a native Unity solution for automating the Unity iOS push notification integration. To take advantage of this option, please ensure that you have followed the Initial SDK Setup steps on setting your Appboy API key through Unity.

Step 1: Open Appboy Configuration Settings

In the Unity Editor, open the Appboy Configuration Settings by navigating to Appboy > Appboy Configuration.

Step 2: Integrating Push With Appboy

Check “Integrate Push With Appboy” to automatically register users for push notifications, pass push tokens to Appboy, track analytics for push opens, and take advantage of Appboy’s default push notification handling.

Integrate Push With Appboy

Users who have not yet opted-in to push notifications will be prompted to opt-in upon opening your application. To disable the automatic opt-in prompt and manually register users for push, see Disabling Automatic Push Registration below.

Note: If you do not check this option, you will not be able to send your users push notifications from the Appboy dashboard without following the manual push notification integration instructions.

Disabling Automatic Push Registration

Check “Disable Automatic Push Registration” if you would like to manually register users with APNs (Apple Push Notification Service). Unity provides NotificationServices.RegisterForNotifications to do this from Unity.

Disable Automatic Push Registration

Note: If you check this option, make sure that you are registering users for push notifications EVERY time the application runs after users have granted push permissions to your app. Apps need to re-register with APNs as device tokens can change arbitrarily.

Enabling Background Push

Check “Enable Background Push” if you would like to enable background mode for push notifications. This allows the system to wake your application from the Suspended state when a push notification arrives, enabling your application to download content in response to push notifications. Checking this option is required for Appboy’s uninstall tracking functionality.

Enabling Background Push

Note: If you build your Xcode project with “Enable Background Push” checked and then later uncheck this option, you will need to either manually disable background push or choose “Replace” when rebuilding your iOS project. You can manually disable background push by removing remote-notifications from the UIBackgroundModes array in your Info.plist.

Step 3: Setting Push Listeners

If you would like to pass push notification payloads to Unity or take additional steps when a user receives a push notification, Appboy provides the option of setting push notification listeners.

Push Received Listener

The Push Received listener is fired when a user receives a push notification while they are actively using the application (i.e., the app is foregrounded). To send the push payload to Unity, set the name of your Game Object and Push Received listener callback method under the “Set Push Received Listener” foldout, like so:

Push Received Listener

For a sample implementation, take a look at the PushNotificationReceivedCallbackForiOS in AppboyBindingTester.cs.

Push Opened Listener

The Push Opened listener is fired when a user launches the app by clicking on a push notification. To send the push payload to Unity, set the name of your Game Object and Push Opened listener callback method under the “Set Push Opened Listener” foldout, like so:

Push Opened Listener

For a sample implementation, take a look at the PushNotificationOpenedCallbackForiOS in AppboyBindingTester.cs.

Manual Push Integration

Step 1: Update Application Code

  • Add the code below to your application:didRegisterForRemoteNotificationsWithDeviceToken method

    [[Appboy sharedInstance] registerPushToken:
                   [NSString stringWithFormat:@"%@", deviceToken]];
    
  • Call the registerForRemoteNotificationTypes: in your application:didFinishLaunchingWithOptions: method

      [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
                (UIRemoteNotificationTypeAlert |
                 UIRemoteNotificationTypeBadge |
                 UIRemoteNotificationTypeSound)];
      [[AppboyUnityManager sharedInstance] addPushReceivedListenerWithObjectName:@"Your Unity Game Object Name" callbackMethodName:@"Your Unity Call Back Method Name"];
      [[AppboyUnityManager sharedInstance] addPushOpenedListenerWithObjectName:@"Your Unity Game Object Name" callbackMethodName:@"Your Unity Call Back Method Name"];
    
  • In your app delegate, add the code below to your application:didReceiveRemoteNotification method:

Method to Count Opens while Foregrounded

Appboy will use this code to determine if a push notification was opened. If the app is foregrounded and a push notification comes in, Appboy will still count the open.

[[AppboyUnityManager sharedInstance] registerApplication:application
                didReceiveRemoteNotification:userInfo];

Alternate Method to Disregard Opens while Foregrounded

If you don’t want to count opens for pushes that come in while the app is foregrounded use the following method instead:

UIApplicationState state = [application applicationState];
if (state != UIApplicationStateActive) {
 [[AppboyUnityManager sharedInstance] registerApplication:application
                 didReceiveRemoteNotification:userInfo];
}

Step 2: Verify Code Modifications

Verify the code modifications you made against this sample AppController.mm file.

Push Customization

iOS Badge Counts

Note: If badge counts are enabled, Appboy will only clear the badge count when the app is opened directly from an Appboy push notification. This is to avoid interfering with any other badges stemming from other notifications within the app.

Manually Clearing the Badge Count

[UIApplication sharedApplication].applicationIconBadgeNumber = 0;

Sample Appboy Apple Push Payload

When Appboy sends a push notification, the payload will look like this. You should avoid handling a top-level dictionary called ab in your application:

{
  aps: {
    alert: {
     body: "your push message",
     title: "your message title"
    },
    badge: 1,
    ...
  },
  ab: {
    c: "your campaign id",
    att: { // optional, required for campaigns with iOS 10 rich notifications
      url: (optional, string) attachment url,
      type: (optional, string) attachment filetype
    },
    ab_cat: { // optional, required for campaigns with push action buttons
      <action_id>: (required) {
        a_t: (required, string) click action type,
        a_uri: (optional, string) uri to open when the push action button is clicked,
        a_use_webview: (optional, boolean) open the a_uri in a UIWebView if true
      },
      ... Other Buttons ...
    },
   }
  ab_uri: (optional, string) uri to open when push notification is clicked,
  ab_use_webview: (optional, boolean) open the ab_uri in a UIWebView if true,
  <custom_key>: "foo",
  ... Custom Key/Value Pairs ...
}

Custom Sounds and Push

Step 1: Hosting the Sound in the App

Custom push notification sounds must be hosted locally within the main bundle of the client application. The following audio data formats are accepted:

  • Linear PCM
  • MA4
  • µLaw
  • aLaw

You can package the audio data in an aiff, wav, or caf file. Then, in Xcode, add the sound file to your project as a nonlocalized resource of the application bundle.

You may use the afconvert tool to convert sounds. For example, to convert the 16-bit linear PCM system sound Submarine.aiff to IMA4 audio in a CAF file, use the following command in the Terminal application:

afconvert /System/Library/Sounds/Submarine.aiff ~/Desktop/sub.caf -d ima4 -f caff -v

You can inspect a sound to determine its data format by opening it in QuickTime Player and choosing Show Movie Inspector from the Movie menu.

Custom sounds must be under 30 seconds when played. If a custom sound is over that limit, the default system sound is played instead.

Step 2: Providing the Dashboard with a Protocol URL for the Sound

Your sound must be hosted locally within the app. You must specify a Protocol URL which directs to the location of the sound file in the app within the “Sound” field pictured below:

Push Notification Sound

For additional information see the Apple Developer Documentation regarding “Preparing Custom Alert Sounds” as well as our resources regarding the use of “Protocol URLs.”

Deep Linking to In-App Resources

See our documentation on Deep Linking in iOS.

In-App Messaging

In-App Message Types

There are four types of in-app messages: slideup, modal, full, and custom HTML. All in-app messages implement Appboy.Models.IInAppMessage.cs, and modal and full in-app messages additionally implement Appboy.Models.IInAppMessageImmersive.cs. These interfaces provide ways in which you can interact with or customize Appboy’s in-app messages.

For more information, see Appboy.Models.InAppMessageBase and Appboy.Models.InAppMessageImmersiveBase.

Customization

Custom in-app messages can be handled in Unity via Appboy’s InAppMessage models.

Logging Clicks and Impressions

In-App Message Body

Clicks and impressions must be manually logged for in-app messages handled in Unity. You can use the LogClicked() and LogImpression() methods defined in Appboy.Models.IInAppMessage.

In-App Message Buttons

Button clicks can be logged by calling the LogButtonClicked(buttonID(int)) method in Appboy.Models.IInAppMessageImmersive. The ButtonID can be retrieved from Appboy.Models.InAppMessageButton.

For more information, refer to Appboy.Models.InAppMessageImmersiveBase.

Customizing Display Behavior

Dismissal Behavior

You can customize in-app message dismissal behavior by setting the in-app message’s InAppDismissType property to either DismissType.AUTO_DISMISS or DismissType.SWIPE.

For more information, see Appboy.Models.InAppMessage.IInAppMessage and Appboy.Models.DismissType.

Slideup Behavior

For slideup in-app messages, you can set in-app messages to slide from the top or bottom by setting the in-app message’s SlideupAnchor property to SlideFrom.TOP or SlideFrom.BOTTOM.

For more information, see Appboy.Models.InAppMessage.InAppMessageSlideup and Appboy.Models.SlideFrom.

Customizing Click Behavior

In-App Messages

To set the in-app click action, you can call SetInAppClickAction() and pass in ClickAction.NEWS_FEED or ClickAction.NONE, which will redirect to the News Feed or do nothing, respectively.

Alternatively, you can set the click action to redirect to a URI by calling

SetInAppClickAction(ClickAction.URI, "https://www.appboy.com");

For more information, see Appboy.Models.InAppMessage.IInAppMessage and Appboy.Models.ClickAction.

In-App Message Buttons

You can also set the click action on an in-app message button via the SetButtonClickAction() methods on Appboy.Models.InAppMessageButton:

SetButtonClickAction(ClickAction.NEWS_FEED);

SetButtonClickAction(ClickAction.URI, "https://www.appboy.com");

Customizing Appearance

While the iOS SDK supports NUI theming for in-app messages, it is not recommended to use NUI theming with Unity. Instead, custom in-app messages should be handled in Unity, using Appboy’s in-app message models.

Sample Code

For sample implementation code, refer to the InAppMessageReceivedCallback() method in AppboyBindingTester.cs.

News Feed

Overview of the News Feed Models

  • The News Feed is represented as a Feed object, which has a list of Card objects
  • Various card models extend the base Card object
  • Cards can additionally be grouped by CardCategory

Retrieving the News Feed

To retrieve the News Feed from Appboy, call either of the following methods:

Both methods will notify your News Feed listener and pass the News Feed along to your callback method.

Logging News Feed Analytics

If you wish to log News Feed analytics, you can do so using the following methods.

Logging Feed Displayed

To log a Feed Displayed event whenever a user views the News Feed, use AppboyBinding.LogFeedDisplayed().

Logging Card Impressions

To log a News Feed Card impression and mark the card as viewed, call the LogImpression() method on the associated Card object.

Logging Card Clicks

To log a News Feed Card click, call the LogClick() method on the associated Card object.

Implementation Example

Check out the FeedReceivedCallback implementation in AppboyBindingTester.cs for an implementation example.

Analytics

Setting User IDs

A user ID should be set for each of your users. These should be unchanging and accessible when a user opens the app. Something like a username, or a unique identifier from your database is usually a good reference to use. We strongly recommend providing this identifier. It will allow you to:

  • Track your users across devices and platforms, improving the quality of your behaviorial and demographic data.
  • Import data about your users using our User API from any source.
  • Target specific users with our Messaging API for both general and transactional messages.

Note:If such an identifier is not available, Appboy will assign a unique identifier to your users, but you will lack the capabilities above.

Time Estimate: 3 Minutes

Assigning a User ID

You should make the following call as soon as the user is identified (generally after logging in) in order to set the user id:

AppboyBinding.ChangeUser("YOUR_USER_ID_STRING");

Note: Do not call ChangeUser() when a user logs out. ChangeUser() should only be called when the user logs into the application. Setting ChangeUser() to a static default value will associate ALL user activity with that default “user” until the user logs in again.

Additionally, we recommend against changing the user ID when a user logs out, as it makes you unable to target the previously logged-in user with reengagement campaigns. If you anticipate multiple users on the same device, but only want to target one of them when your app is in a logged out state, we recommend separately keeping track of the user ID you want to target while logged out and switching back to that user ID as part of your app’s logout process.

Automatic Preservation of Anonymous User History

Identification Context Preservation Behavior
User has not been previously identified Anonymous history is merged with user profile upon identification
User has been previously identified in-app or via API Anonymous history is not merged with user profile upon identification

Additional Notes and Best Practices

Please note the following:

  • If your app is used by multiple people, you can assign each user a unique identifier to track them.
  • Once a user ID has been set, you cannot revert that user to an anonymous profile
  • Do Not change the user ID upon a user “log out”.
    • Doing so separates the device from the user profile. You will be unable to target the previously logged out user with re-engagement messages. If you anticipate multiple users on the same device, but only want to target one of them when your app is in a logged out state, we recommend separately keeping track of the user ID you want to target while logged out and switching back to that user ID as part of your app’s logout process. By default, only the last user that was logged in will receive push notifications from your app.
  • Switching from one identified user to another is a relatively costly operation.
    • When you request the user switch, the current session for the previous user is automatically closed and a new session is started. Furthermore, Appboy will automatically make a data refresh request for the news feed, slideup and other Appboy resources for the new user.
  • Note: If you opt to use a hash of a unique identifier as your userID take care to ensure that you’re normalizing the input to your hashing function.
    • e.g. If you’re going to use a hash of an email address, ensure that you’re stripping leading and trailing whitespace from the input, and taking localization problems into account.

Logging Custom Events

You can record custom events in Appboy to learn more about your app’s usage patterns and to segment your users by their actions on the dashboard.

Before implementation, be sure to review examples of the segmentation options afforded by Custom Events vs. Custom Attributes vs Purchase Events in our Best Practices section.

Time Estimate: 5 Minutes

AppboyBinding.LogCustomEvent("event name");

Appboy also supports adding metadata about custom events by passing a Dictionary of event properties:

AppboyBinding.LogCustomEvent("event name", properties(Dictionary<string, object>));

Note: In versions of the SDK prior to 1.8.0, the properties Dictionary only supports string values.

REST API

You can also use our REST API to record events. Refer to the user API documentation for details.

Setting Custom Attributes

Appboy provides methods for assigning attributes to users. You’ll be able to filter and segment your users according to these attributes on the dashboard.

Before implementation, be sure to review examples of the segmentation options afforded by Custom Events vs. Custom Attributes vs Purchase Events in our Best Practices section.

Time Estimate: 5 Minutes

Assigning Standard User Attributes

To assign user attributes, you need to call the appropriate method on the AppboyBinding object. The following is a list of built-in attributes that can be called using this method.

First Name

AppboyBinding.SetUserFirstName("first name");

Last Name

AppboyBinding.SetUserLastName("last name");

User Email

AppboyBinding.SetUserEmail("email@email.com");

Note: It’s still valuable to set email addresses even if you’re not sending emails through Appboy. Email makes it easier to search for individual user profiles and troubleshoot issues as they arise.

User Bio

Note: AppboyBinding.SetUserBio() has been deprecated.

Gender

AppboyBinding.SetUserGender(Appboy.Models.Gender.Male or Appboy.Models.Gender.Female);

Birth Date

AppboyBinding.SetUserDateOfBirth("year(int)", "month(int)", "day(int)");

User Country

AppboyBinding.SetUserCountry("country name");

User Home City

AppboyBinding.SetUserHomeCity("city name");

User Email Subscription

AppboyBinding.SetUserEmailNotificationSubscriptionType(AppboyNotificationSubscriptionType.OPTED_IN or AppboyNotificationSubscriptionType.SUBSCRIBED or AppboyNotificationSubscriptionType.UNSUBSCRIBED);

Note: AppboyBinding.SetUserIsSubscribedToEmails() has been deprecated. Please use AppboyBinding.SetUserEmailNotificationSubscriptionType() instead.

User Push Subscription

AppboyBinding.SetUserPushNotificationSubscriptionType(AppboyNotificationSubscriptionType.OPTED_IN or AppboyNotificationSubscriptionType.SUBSCRIBED or AppboyNotificationSubscriptionType.UNSUBSCRIBED);

User Phone Number

AppboyBinding.SetUserPhoneNumber("phone number without hyphens");

User Avatar Image URL

AppboyBinding.SetUserAvatarImageURL("URL");

Assigning Custom User Attributes

Beyond the attributes above, Appboy also allows you to define Custom Attributes using a number of different data types: For more information regarding the segmentation options each of these attributes will afford you see our “Best Practices” documentation within this section.

Custom Attribute with a Boolean Value

AppboyBinding.SetCustomUserAttribute("custom boolean attribute key", 'boolean value');

Custom Attribute with an Integer Value

// Set Integer Attribute
AppboyBinding.SetCustomUserAttribute("custom int attribute key", 'integer value');
// Increment Integer Attribute
AppboyBinding.IncrementCustomUserAttribute("key", increment(int))

Custom Attribute with a Double Value

AppboyBinding.SetCustomUserAttribute("custom float attribute key", 'float value');

Note: Appboy treats FLOAT and DOUBLE values exactly the same within our database.

Custom Attribute with a String Value

AppboyBinding.SetCustomUserAttribute("custom string attribute key", "string custom attribute");

Custom Attribute with a Date Value

AppboyBinding.SetCustomUserAttributeToNow("custom date attribute key");
AppboyBinding.SetCustomUserAttributeToSecondsFromEpoch("custom date attribute key", 'integer value');

Custom Attribute with an Array Value

// Setting An Array
AppboyBinding.SetCustomUserAttributeArray("key", array(List), sizeOfTheArray(int))
// Adding to an Array
AppboyBinding.AddToCustomUserAttributeArray("key", "Attribute")
// Removing an item from an Array
AppboyBinding.RemoveFromCustomUserAttributeArray("key", "Attribute")

Note: Dates passed to Appboy must either be in the ISO 8601 format, e.g 2013-07-16T19:20:30+01:00 or in the yyyy-MM-dd'T'HH:mm:ss.SSSZ format e.g 2016-12-14T13:32:31.601-0800

Unsetting a Custom Attribute

Custom Attributes can also be unset using the following method:

AppboyBinding.UnsetCustomUserAttribute("custom attribute key");

Setting a Custom Attribute via the REST API

You can also use our REST API to set user attributes. To do so refer to the user API documentation.

Custom Attribute Value Limits

Custom attribute values have a maximum length of 255 characters; longer values will be truncated.

Setting Up User Subscriptions

To set up a subscription for your users (either email or push), call the functions
AppboyBinding.SetUserEmailNotificationSubscriptionType() or AppboyBinding.SetPushNotificationSubscriptionType(), respectively. Both of these functions take the parameters Appboy.Models.AppboyNotificationSubscriptionType as arguments. This type has three different states:

Subscription Status Definition
OPTED_IN Subscribed, and explicitly opted in
SUBSCRIBED Subscribed, but not explicitly opted in
UNSUBSCRIBED Unsubscribed and/or explicitly opted out

Note: No explicit opt-in is required by Windows to send users push notifications. When a user is registered for push, they are set to SUBSCRIBED rather than OPTED_IN by default. For more information on implementing subscriptions and explicit opt-ins, visit the topic on Appboy Academy.

  • EmailNotificationSubscriptionType
    • Users will be set to SUBSCRIBED automatically upon receipt of a valid email address. However, we suggest that you establish an explicit opt-in process and set this value to OPTED_IN upon receipt of explicit consent from your user. See Appboy Academy for details.
  • PushNotificationSubscriptionType
    • Users will be set to SUBSCRIBED automatically upon valid push registration. However, we suggest that you establish an explicit opt-in process and set this value to OPTED_IN upon receipt of explicit consent from your user. See Appboy Academy for details.

Note: These types fall under Appboy.Models.AppboyNotificationSubscriptionType.

Sample Code

Email Subscription:

AppboyBinding.SetUserEmailNotificationSubscriptionType(AppboyNotificationSubscriptionType.OPTED_IN);

Push Notification Subscription:

AppboyBinding.SetUserPushNotificationSubscriptionType(AppboyNotificationSubscriptionType.OPTED_IN);

Logging Purchases

Record in-app purchases so that you can track your revenue over time and across revenue sources, as well as segment your users by their lifetime value.

Appboy supports purchases in multiple currencies. Purchases that you report in a currency other than USD will be shown in the dashboard in USD based on the exchange rate at the date they were reported.

Before implementation, be sure to review examples of the segmentation options afforded by Custom Events vs. Custom Attributes vs Purchase Events in our Best Practices section.

Time Estimate: 3-5 Minutes

To use this feature, add this method call after a successful purchase in your app:

AppboyBinding.LogPurchase("productId", "currencyCode", price(decimal));

The above method logs a purchase with a quantity of 1. If you would like to pass in a different quantity, you can call this method:

AppboyBinding.LogPurchase("productId", "currencyCode", price(decimal), quantity(int));

Quantity must be less than or equal to 100. Appboy also supports adding metadata about purchases by passing a Dictionary of purchase properties:

AppboyBinding.LogPurchase("productId", "currencyCode", price(decimal), quantity(int), properties(Dictionary<string, object>));

Note: In versions of the SDK prior to 1.8.0, the properties Dictionary only supports string values.

Currency Codes

Supported currency symbols are listed below. Any other provided currency symbol will result in a logged warning and no other action taken by the SDK.

  • USD, AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTC, BTN, BWP, BYR, BZD, CAD, CDF, CHF, CLF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EEK, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GGP, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, IMP, INR, IQD, IRR, ISK, JEP, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LTL, LVL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRO, MTL, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLL, SOS, SRD, STD, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, UYU, UZS, VEF, VND, VUV, WST, XAF, XAG, XAU, XCD, XDR, XOF, XPD, XPF, XPT, YER, ZAR, ZMK, ZMW and ZWL.

Sample Code

AppboyBinding.LogPurchase("product ID", "USD", 12.5m);

REST API

You can also use our REST API to record purchases. Refer to the user API documentation for details.

Advanced Use Cases

Customizing the Unity Package

You can choose to customize and export the Appboy Unity package using the provided scripts.

  1. Clone the Appboy Unity SDK Github project:

    bash git clone git@github.com:Appboy/appboy-unity-sdk.git

  2. From the root appboy-unity-sdk directory, run ./scripts/generate_package.sh to export the Unity package.
    • Adding the --nodeps command line option will bundle the Unity package without the SDWebImage iOS SDK dependency. Please note that SDWebImage is required for proper functionality of Appboy’s In-App Messaging and News Feed features on iOS.
    • Note: Unity CANNOT be open while running generate_package.sh, or the script will fail.
  3. The package will be exported to unity-package/Appboy.unitypackage.
    • If you generated the package with the --nodeps option, it will be named Appboy-nodeps.unitypackage.
  4. In the Unity Editor, import the package into your Unity project by navigating to Assets > Import Package > Custom Package.
  5. (Optional) Deselect any files you do not wish to import.

You can customize the exported Unity package by editing both generate_package.sh and the export script located at Assets/Editor/Build.cs.

Troubleshooting

File Could Not Be Read Errors

Errors resembling the following may be safely ignored. Apple software uses a proprietary PNG extension called CgBI, which Unity does not recognize. These errors will affect neither your iOS build nor proper display of the associated images in the Appboy bundle.

Could not create texture from Assets/Plugins/iOS/AppboyKit/Appboy.bundle/...png: File could not be read