Last modified June 3, 2016 by Shelly Wolfe

Unity

Swrve is a single integrated platform that delivers everything you need to drive mobile engagement and create valuable customer relationships on mobile.

The Swrve Unity SDK enables your app to use all of the features available. This guide contains all the information you need to integrate the SDK into your app.


Requirements

  • This guide assumes you have already installed Unity on your development machine. We recommend using the latest version of Unity 3D.
  • The App ID and API Key for your app. This information is available in Swrve on the Integration Settings screen (on the Setup menu, click Integration Settings).

Not Supported

  • Unity Web Player
  • Windows 8

Native Plugins

Two features in the Swrve Unity SDK—Conversations and Location-based Campaigns—require native plugins to function in the Unity environment. This means there are some tool requirements:

  • Android – To support Android builds, use the latest version of Unity. For more information about changes to the build process as of version 4.5.X, see the Unity SDK Upgrade Guide.

Installing the SDK

Swrve has an open source SDK repository. There are two options for downloading the latest public Swrve Unity SDK:

Amazon SDK Dependency

If compiling the Amazon-flavored SDK for Unity from source, it is necessary to also download the Amazon SDK from the Amazon Developer portal to get the Amazon Device Messaging (ADM) jar support file (amazon-device-messaging-1.0.1.jar). Add the ADM jar file to your project in the appropriate folders (normally native/android/SwrveSDKPushSupport/providedLibs/). NOTE: Never put the JAR inside Assets/Plugins/Android, if you do that then it will always complain about stub implementations even when running on an Amazon device.

The corresponding project build.gradle files refer to the jar file using the “provided” directive, which, when combined with the Amazon flavor SDK, becomes amazonProvide as follows:

The providing directive tells the library or plugin to compile against the jar but not include the class implementations. They are simply stub implementations and will fail if actually executed. The runtimes exist on the Kindle device.

Debug applications (apk) built using Gradle and being built from source may also need to make use of the amazonProvided directive pointing to the adm jar in their own build.gradle dependency section. This isn’t required for release.

Basic Integration

Complete the following steps for a basic integration.

Step 1: Unzip the Unity SDK, import the Swrve.unityPackage into your project and add the SwrvePrefab component to your scene.

Firebase – To integrate the Firebase-flavored SDK, import the SwrveFirebase.unityPackage into your project instead. The SwrveFirebase.unityPackage differs from the Swrve.unityPackage in that it contains a different FCM version of the SwrveSDKPushSupport.

Amazon – To integrate the Amazon-flavored SDK, import the SwrveAmazon.unityPackage into your project instead. The SwrveAmazon.unityPackage differs from the Swrve.unityPackage in that it contains a different ADM version of the SwrveSDKPushSupport Android plugin and doesn’t include Google Play support plugins.

Step 2: Initalize the Swrve component. There are two methods to initialize the SDK component—automatic initialization and manual initialization. In almost all cases, you should use manual initialization to be able to do advanced setup.

Manual initialization:

Ensure that the “initialize on start” property is disabled in the Swrve prefab and initialize the SDK from a script set to execute at the start of your app:

Automatic initialization:

Set the <app_id> and <api_key> fields of the component in your scene to your Swrve App ID and Swrve API Key and ensure that “initialize on start” is enabled.

Firebase – Set the Config-> AndroidPushProvider value to GOOGLE_FIREBASE, instead of the default GOOGLE_GCM.

Amazon – Set the Config-> AndroidPushProvider value to AMAZON_ADM, instead of the default GOOGLE_GCM, and set the Config-> AppStore to amazon.

Depending on your data requirements, Swrve stores all customer data and content in either our US or EU data centers. If you require EU data storage, include the EU stack information in the example above to configure the SDK to point to Swrve’s EU-based URL endpoints. If you have any questions or need assistance configuring the SDK for EU data storage, please contact support@swrve.com.
To add a custom define in your project, see the Unity article Platform Dependent Compilation.

You can now compile and run your project in Unity.

Step 3: Go to Edit > Project Settings > Script Execution Order and move SwrveComponent to a higher priority in the list. This prevents you from getting a NullReferenceException that can occur if Swrve is called before the SDK has finished initializing.

Basic integration of the Swrve SDK enables you to track important metrics and run in-app message campaigns. To make use of additional Swrve features, such as Conversations, push notifications and advanced metrics tracking, complete the relevant sections as required.

Reducing App Size or Excluding Features

By default, the Swrve.unityPackage now includes all native plugins. If you want to reduce the size of your app or exclude certain features, refer to the following sections.

Remove Push Libraries in Android

To remove Google Cloud Messaging (GCM) / Firebase Cloud Messaging (FCM) or push from your Android build, you can remove the following files from Assets/Plugins/Android:

  • play-services-gcm-*
  • firebase-messaging-*
  • SwrveSDKPushSupport

Limited Build Options for Windows 10

The Unity SDK now includes beta support for developing for Windows 10 or Universal Windows. No additional steps are required to integrate, however it’s only possible to build it as a C# project.

  • To set the build settings in the Unity Editor, in the Build Settings, select Unity C# Projects:
    unity_projects
  • Or, to set the build settings in the code, use the following:

Advertising Identifier (IFDA) Logging

IDFA logging is disabled by default. To log IDFA, add the SWRVE_LOG_IDFA flag to your project settings as shown in the Unity documentation, Platform Dependent Compilation. Enable the configuration flag LogAppleIDFA.


In-App Messages and Conversations

Swrve’s in-app messages campaigns are available as soon as you complete the basic integration described above. Conversations and location-based campaigns require a few extra steps to set up; see the following section for instructions. These features enable you to send personalized messages to your app users while they’re using your app. For more information, see Intro to In-App Messages and Intro to Conversations.

To test in-app messages or Conversations in your app, you need to first create the campaign in Swrve. For more information, see Creating In-App Messages and Creating Conversations.

Unity has no understanding of an active window state, therefore you must include code to pause the app when an in-app message is displayed and resume it as soon as it is closed.

Conversations and Location-Based Campaigns

Conversations and location-based campaigns in Unity Android and Unity iOS use native code. To enable them correctly, follow the below integration steps.

Android

The SDK uses the AAR libraries shared with the native Android SDK. These are distributed as AAR and expanded AAR files within .unityPackage.

Replace ${applicationId} in the libraries with your application ID. Even the latest version of Unity doesn’t support modern features from Android, such as the use of ${applicationId} in AndroidManifest.xml files. Due to this, any Swrve plugins that contain ${applicationId} are set up as an Android Library Project Folder in Unity, and before building for Unity, you must run SwrveBuildComponent.AndroidPrebuild(), which replaces ${applicationId} with your project’s bundle ID. If you’re running continuous integration (CI) builds, it’s best to call this before every Android build.

There is also a helper menu item to do this: Swrve -> Android Prebuild in AndroidManifests.

If you encounter problems while building for Android, it’s most likely due to packaging issues around the AAR files. Use the latest version of Unity to fix these issues.

Beware that if your builds have different application IDs, you will have to rerun this process.

In-App Message and Conversation Deeplinks

When creating in-app messages and Conversations in Swrve, you can configure message buttons to direct users to perform a custom action when clicked. For example, you might configure a button to direct the app user straight to the app store to provide a rating.

Swrve’s default deeplink behavior is to treat custom actions as URLs, therefore use your existing custom URL scheme. Custom URL schemes need to be configured on a per-platform basis.

Once the custom URL scheme is set, your app can receive and direct users from outside of the app.

If you would like to process the custom action completely on your own, you must add a custom listener to the Swrve SDK before its initialization.

In-App Message Custom Actions

For in-app messages, it is also possible to override this behavior of treating custom actions as URL deeplinks and integrate custom actions to direct users to a sale, website or other target when they click on an in-app message. Use the following callback:

For example, to send Swrve events using custom actions, add a customButtonCallback like this:


Push Notifications

Swrve’s push notification campaigns enable you to send personalized messages to your app users while they’re outside of your app or to send silent background app updates. Swrve Push Notifications are available for iOS and Android. For more information, see Intro to Push Notifications.

Push notifications are disabled by default. To enable them, complete the following steps:

Changes to SwrveComponent.Instance.Config must occur before calling SwrveComponent.Instance.Init.

Step 1: Enable push notifications in the SwrveConfig object.

Google

For Android (Google) Push Notifications, you must provide the project number obtained from the Google Developer Console to the SDK on initialization:

Firebase

Amazon

Step 2: Time the push permission request.

To request permission upon the triggering of certain events, include the following code:

Step 3: If you want to perform custom processing of the push notification payload, create the following class and add this code to the SDK initialization:

If you would like to use a custom key-value pair with a notification, for example, to reward a user with points or a new tier, it would make sense to use the Custom Push Notification listener:

Step 4: Follow the platform specific steps below for iOS, Android and Amazon.

Configuring Silent Notifications

To enable silent push notifications in your app, complete the following steps for the relevant platform.

The purpose of a silent notification is to deliver data to your app in the background, such as a content update. You should never call the SDK from a silent notification.

Android (GCM, FCM and ADM)

Step 1: Use or create an Android Library project that will generate an .aar. Later, you will need to place the .aar file in your Plugins/Android folder.

Step 2: Create a BroadcastReceiver to listen to the Swrve Silent Push payload:

Step 3: Add the BroadcastReceiver to your AndroidManifest.xml:

iOS

Step 1: In your Plugins/iOS folder, create a file called SwrveSilentPushListener.h:

Step 2: In your Plugins/iOS folder, create a file called SwrveSilentPushListener.mm:

Platform-Specific Steps for iOS Push Notifications

Creating and Uploading Your iOS Certificate

To enable your app to send push notifications to iOS devices, you require a push certificate. A push certificate authorizes an app to receive push notifications and authorizes a service to send push notifications to an app. For more information, see How Do I Manage iOS Push Certificates?

Provisioning Your App

Each time your app is published for distribution, you must provision it against the push certificate that has been created for the app.

Notification Service Extension for Swrve Rich Push

As of Swrve SDK version 4.11, it is now possible to include rich media options in your push notification content. To display rich push notifications in your app, iOS uses a notification service app extension. The Unity SDK generates an app extension in Xcode as part of the iOSPostProcess.cs class, using the PlayerSettings.ApplicationIdentifier (formerly PlayerSettings.bundleIdentifier in earlier Unity versions) and PlayerSettings.iOS.appleDeveloperTeamID to generate and certify the bundle. To ensure maximum compatibility and ease of use, please ensure you have set the app bundle identifier. To view the bundle identifier in a standard Unity 2017.1 project, on the Edit menu, click Project Settings, and then click Player. Ensure you set both the Bundle Identifier and Team ID.

Unity app bundle identifier

On iOS 10, there is an intermittent issue with notification service extensions where, in some debugging instances, the rich media attachment is not displayed. This is a common issue that has been raised with Apple, but should not affect the production version.

If you are managing provisioning profiles for your app, you must create one for your service extension as well.

Tracking Influenced Users

As of Swrve SDK version 4.10 and the addition of silent notifications, Swrve automatically tracks influenced metrics (that is, if a user opens your app within a certain window after receiving the silent notification). Prior to SDK version 4.11, influenced events were only sent for silent notifications, however it is now possible to track influenced from all push notifications. For Android, this is enabled without any further interaction, however to do so on iOS, the application needs to share stored information with the service extension. An app group enables the service extension to save the influenced data to shared container that the main app can access on startup. To track influenced users, you must provide a iOSAppGroupIdentifier key that the SDK will use in the postprocess.json file.

To add an app group and specify the iOSAppGroupIdentifier key:

Step 1: In the Apple Developer portal, create a new App Group. Enter the description and name as group.BundleID (the BundleID is the same as the PlayerSettings.ApplicationIdentifer).

Step 2: On the portal, go to your app ID for your main app, add the App Group capability and select your new App Group in the checkbox provided.

When you check the Application Services on the portal, App Groups should be enabled.

app groups enabled

Step 3: Repeat the above step for the app extension.

Step 4: If your provisioning profiles are not handled by Xcode, you will need to regenerate them as adding an app groups will make them invalid. For example:

regenerate provisioning profile

Select the profile, click Edit and then click Generate. It is not necessary to make a new provisioning profile, as the status will change to Valid after you click Generate.

Step 5: Add the following key and app group identifier (that you created in Step 1) to the postprocess.json file located in unity3d/Assets/Swrve/Editor directory of the SwrveSDK.

"iOSAppGroupIdentifier": "group.com.your.group.name"

Step 6: Build your Unity project for iOS. In the resulting Xcode project, you should see a new target for the service extension and the app group set in the capabilities section. Ensure that the provisioning profiles and capabilities are set correctly.

Step 7: Run the application.

Send a rich push notification to your QA device, do not interact with it but open the app directly and you should see influenced events coming in to your reporting. (Test push notifications have the ID of 0).

iOS Notification Categories

The Swrve Unity SDK uses the UserNotifications.framework introduced in iOS 10. This requires the use of the new UserNotifications objects provided by Apple. In the SwrveSDK, we have added a new class to handle UNNotificationCategories, which can be grouped as a list and passed into the new SwrveConfig property notificationCategories. If you still want to support pre-iOS 10 notifications, you can still make UIUserNotificationCategories and pass them into pushCategories as you did before. They have not been affected.

Swrve includes a C# version of the notification categories defined by Apple. For more information on each individual function, please see the Apple UNNotification Category documentation.

Platform-Specific Steps for Android Push Notifications

Unity Android uses a native Android plugin provided as part of the Unity SDK located under Assets/Plugins/Android/SwrveSDKPushSupport.

By default, the config-> AndroidPushProvider value is set to GOOGLE_GCM. If you are using Firebase Cloud Messaging (FCM), change this value to GOOGLE_FIREBASE. If you are using Amazon Device Messaging (ADM), use AMAZON_ADM.

Unity does not automatically replace the ${applicationId} with your app’s package name. To do that we offer a tool in the menu Swrve-> Android Prebuild in AndroidManifests. You can also manually replace the value with the package name of your app.

Firebase Cloud Messaging

Complete the following steps if you are using FCM instead of GCM.

Step 1: Create an Android library.

Step 2: Add the following file with the correct details extracted from your Firebase Console under src/main/res/values.xml:

Step 3: Build the project into an .aar or .jar and place it under your project’s Assets/Plugins/Android.

Using a Custom GCM / FCM Receiver

If you are already using push notifications, follow the instructions below to integrate Swrve’s push notification functionality.

Add the following lines to the onReceive method of your custom GcmReceiver (for FCM, replace gcm with firebase):

Custom Main Activity

If you have a custom MainActivity, call the following functions onCreate and onResume:

Firebase

Amazon – Replace any instances of gcm with adm

No Custom Main Activity

If you don’t provide a custom MainActivity, point to Swrve’s MainActivity in your AndroidManifest.xml:

Google

Firebase

Amazon

Advanced Android Push

This section describes how to configure advanced options for Unity SDK push notification integration.

Using Custom Icons

To change the icon for push notifications and your app, place a file called app_icon.png under Assets/Plugins/Android/res/drawable/. You can also provide multiple resolutions for the same asset. Please consult the Android documentation on how to do so.

You can also specify the resource to be used for the normal and Material icon with the following configuration properties

Firebase – Replace any instances of GCM with FIREBASE

Amazon – Replace any instances of GCM with ADM

Configuring Android O Notification Channels

With Android O, Google has introduced the concept of notifications channels. As of Swrve Unity SDK 4.11+, you can configure your default Android O channel. To do so, create an AndroidChannel and set it before initializing the SDK in your SwrveConfig object:

Using Custom Sounds

You can send push notifications with custom sounds. To do so, place your custom sound under Assets/Plugins/Android/res/raw and set your sounds in the Swrve service. For more information about adding custom sounds in Swrve, see Intro to Push Notifications.

Platform-Specific Steps for Amazon Push Notifications

Application Signing

If you do your own application signing, you need to add the Amazon api_key.txt to the Android plugins folder of your project. To get this key from Amazon, follow this guide on Obtaining Amazon Device Messaging Credentials.

Copy your Amazon api_key.txt file to unity folder Assets/Plugins/Android/assets.

Note the keystore and password relate to those used in PlayerSettings (Android) > Publishing Settings > Keystore > Browse Keystore.

Amazon Namespace

As of version 5.4.+, Unity does not automatically include non-Android namespaces (xmlns:) and their elements from plugin manifests in the final Unity-generated APK Android manifest. You need to manually add the Amazon namespace and enable-feature element to the root manifest in Assets/Plugins/Android.

If you don’t have a root manifest, the default debug Unity manifest looks like the following as of Unity version 5.4.1 (including the Amazon modifications). You would also need to alter the activity name to point to either a custom Main activity or the Swrve Main activity (see the previous Android sections for details).

Creating and Entering the Amazon Client ID and Client Secret

To enable your app to send push notifications to Amazon devices, you need the Client ID and Client Secret for your app. For information on how to get these credentials, see Obtaining Amazon Device Messaging Credentials.

Generally, you enter the Client Id and Client Secret on the Swrve dashboard when configuring the Integration Settings as part of the Swrve onboarding process. You can edit the settings on this screen later on if required.

Step 1: On the Setup menu, click Integration Settings.

Step 2: Under the Push Notifications section, in the Amazon Device Messaging Service section, enter your Client Id and Client secret.

Step 3: Test the server key by sending a test push notification to one of your QA devices. To send a test push notification:

  • Select your QA device from the list of available devices.
  • Click Send Test Push.

Sending Events

The Swrve SDK automatically sends certain events and also enables you to track user behavior by sending custom events. (For a list of default Swrve events, see About Audience Filters, Events.) In turn, you can use app-generated events to trigger in-app messages, while both app- and server-generated events help you define segments and perform in-depth analytics.

Custom Events

To send a custom event, include the below example in a method where you want to send an event to Swrve.

Requirements for sending custom events:

  • Do not send the same named event with different case. For example, if you send tutorial.start, then ensure you never send Tutorial.Start.
  • Use a period (.) in your event names to organize their layout in the Swrve dashboard. Each ‘.’ creates a new branch in the Event name column of the Events report, and groups your events so they are easy to locate.
  • Do not send more than 1000 unique named events.
    • Do not add unique identifiers to event names. For example, Tutorial.Start.ServerID-ABDCEFG
    • Do not add timestamps to event names. For example, Tutorial.Start.1454458885
  • Do not use the swrve.* or Swrve.* namespace for your own events. This is reserved for Swrve use only. Custom event names beginning with Swrve. are restricted and cannot be sent.

Event Payloads

You can add and send an event payload with every event. This allows for more detailed reporting around events and funnels.

Notes on associated payloads:

  • The associated payload should be a dictionary of key/value pairs; it is restricted to string and integer keys and values.
  • There is a maximum cardinality of 500 key-value pairs for this payload per event. This parameter is optional, but only the first 500 payloads are displayed in the dashboard. The data is still available in raw event logs.
  • It is not currently possible to use payloads as triggers for push notifications or for audience filters in the dashboard. Use events for these purposes.

For example, if you want to track when a user starts the tutorial experience, it might make sense to send an event named tutorial.start and add a payload time that captures how much time it took the user to complete the tutorial.

Custom User Properties

The Swrve SDK sends certain user properties by default and also enables you to assign custom properties to update the user’s status. (For a full list of the default user properties, see Assigning User Properties.)

For example, you could create a custom user property called premium, and then target non-premium users and premium users in your campaigns.

Example of group of user properties

Example of single date-typed user property

Use the DateTime object to send a DateTime user property; for example, the current date at the time of a user purchase:

Virtual Economy Events

To ensure virtual currency events are not ignored by the server, make sure the currency name configured in your app matches exactly the Currency Name you enter in the App Currencies section on the App Settings screen (including case-sensitive). If there is any difference, or if you haven’t added the currency in Swrve, the server will ignore the event and return an error event called Swrve.error.invalid_currency. Additionally, the ignored events are not included in your KPI reports. For more information, see Add Your App.

If your app has a virtual economy, send the purchase event when users purchase in-app items with virtual currency.

Send the currency given event when you give users virtual currency. Examples include initial currency balances, retention bonuses and level-complete rewards.

In-App Purchase Events and Validation

If your app has in-app purchases (IAPs), send the IAP event when a user purchases something with real money.

  • In iOS 7+ devices, Apple returns a receipt including multiple purchases. To identify what was purchased, Swrve needs to be sent the transactionID of the item purchased (see SKPaymentTransaction::transactionIdentifier).
  • In iOS 6 and lower, Apple only returns one transaction per receipt, so the Swrve IAP method without the transactionId can be used.
  • If paymentProvider was Apple, use either Base64EncodedReceipt or RawReceipt, depending on whether the receipt is already encoded. Third party Unity IAP plugins can return the receipt already encoded (and this behavior may be different between iOS7+ receipts and iOS6 receipts).
  • For Google Play, the receipt and receiptSignature should be provided.
  • For other platforms (including Amazon), no receipt validation is available.

If the purchase is of an item, and not a currency, you can omit the rewards argument:

The correct Apple bundle ID (iOS) or the Google Server Validation Key (Android) should be added to the Integration Settings screen in Swrve. This allows Swrve to validate purchases made in the app.


Resource A/B Testing

Integrating Swrve’s resource A/B testing functionality enables you to use Swrve to test how users respond to changes to the native app content. For more information about resource A/B testing, see Intro to Resource A/B Testing.

To get the latest version of a resource from Swrve using the Resource Manager, use the following:

If you want to be notified whenever resources change, you can add a callback function as follows:


Testing Your Integration

After you’ve completed the above, the next step is to test the integration. For more information, see Testing Your Integration.


Upgrade Instructions

If you’re moving from an earlier version of the Unity SDK to the current version, see the Unity SDK Upgrade Guide for upgrade instructions.


SDK Demo

For a general demo of the Swrve Unity SDK, see the Swrve Unity SDK demo on Github.