Last modified January 12, 2024 by Shelly Wolfe

Cordova (PhoneGap)

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

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


Requirements

  • The App ID and API Key for your app. This information is available in Swrve on the Integration Settings screen (on the Settings menu, select Integration settings).
  • Note: The Cordova plugin uses the native SDKs for iOS and Android. You can find more information about the native SDKs in the platform-specific documentation.
  • NPM version 6.7.0 or above.
  • Cordova Command-Line Interface (CLI) version 12.0.0.
  • cordova-ios 7.0.1.
  • cordova-android 12.0.1.

Installing the SDK

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

  • Install the plugin from NPM using the following command:
    cordova plugin add cordova-plugin-swrve
  • Download the plugin from the GitHub public repository or clone the repository.

Initializing the SDK Plugin from a template

To help you quickly get started with an empty project that already includes the Swrve config, we’ve provided a template using the Cordova App Templates pattern. Use the Cordova CLI to check out this repository and build it as a project. For example:

cordova create hello com.example.hello HelloWorld --template https://github.com/Swrve/swrve-cordova-minimal-integration.git

Change hello, com.example.hello, and HelloWorld to fit the application directory name, bundle identifier, and name you need.

Once the template is created, edit the properties of config.xml as needed The following section describes how to modify your config.xml.


Adding the SDK Plugin to your project

To simplify project initialization, the Swrve Cordova SDK plugin uses Hooks to generate the majority of the settings and code in the final project. This also makes it easier to upgrade to future versions of iOS and Android Cordova.The plugin includes two scripts and boilerplate code that are used during the after_plugin_install and after_prepare lifecycle states of a Cordova build. To activate them and add your own settings, you must perform the following steps:

Step 1: Add the Swrve Cordova SDK plugin to your project:

cordova plugin add cordova-plugin-swrve

Step 2: Modify the config.xml at the root of your Cordova/PhoneGap project as shown in the platform-specific examples below. Replace <swrve_app_id> and <swrve_api_key>  with your own app ID and API key.

Depending on your data requirements, Swrve stores all customer data and content in either our US or EU data centers. If your app uses EU data storage and URL endpoints (that is, you log into the Swrve dashboard at https://eu-dashboard.swrve.com), include the EU stack information in the example below. If you have any questions or need assistance configuring the SDK for EU data storage, please contact support@swrve.com.

iOS

Note: We do not manage application signing or entitlements on the main app. You need to add your own config.xml changes to handle things like remote notifications. (See Push Notifications for more information.)

<platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
    <preference name="swrve.appId" value="<swrve_app_id>" />
    <preference name="swrve.apiKey" value="<swrve_api_key>" />
    <!-- To use the EU stack, include this in your config.xml -->
    <!-- <preference name="swrve.stack" value="EU" /> -->
</platform>

Android

<platform name="android">
    <allow-intent href="market:*" />
    <preference name="android-compileSdkVersion" value="33" />
    <preference name="android-targetSdkVersion" value="33" />
    <preference name="swrve.appId" value="<swrve_app_id>" />
    <preference name="swrve.apiKey" value="<swrve_api_key>" />
    <!-- To use the EU stack, include this in your config.xml -->
    <!-- <preference name="swrve.stack" value="EU" /> -->
</platform>

Step 3: Add both platforms via Cordova CLI. If you plan on using push notifications, leave this step until you have completed the Push Notifications section of this guide. Otherwise, use the following commands to generate your project.

cordova platform add android
cordova platform add ios

Advanced initialization mode

As of Cordova Plugin version 2.1, there are two modes for initializing the SDK: AUTO and MANAGED. In AUTO mode, the SDK is automatically initialized as outlined in the previous section. However, if you want to delay the point at which the SDK starts tracking and sending events for a particular user, set the swrve.initMode property in the config.xml to SwrveInitMode.MANAGED.  For example, you might want to use a custom ID as the Swrve user ID and not start sending events or targeting a customer until they’ve confirmed their user ID (that is, they’ve logged in).

Do not use email or other personally identifiable information (PIIs) for the custom user ID, as this could be used to compromise your app or integration. Instead, use an internal ID that is only known to your CRM and cannot be linked back to a user outside of your system.
<preference name="swrve.initMode" value="MANAGED" />
<preference name="swrve.managedModeAutoStartLastUser" value="true" />

If you use MANAGED mode, the SDK will delay tracking by default until the user ID is set at least once via the start API.

window.plugins.swrve.start("<user_id>",
  function(response) {/** Success, continue with your logic */},
  function(response) {/** Error, should be handled  */}
);

Constraints and considerations

Depending on the initialization mode you choose to use, there are certain limits or nuances you should be aware of:

  • In MANAGED mode, you can’t call the Identify API. If you try to call the Identify API, it will result in a fail fast exception.
  • In AUTO (default) mode, you can’t call the following APIs. If you try to call them, it will result in a fail fast exception:
    • Start()
    • Start(userId)
  • In-app campaigns linked to a push notification are blocked in configurations where:
    • swrve.initMode is “MANAGED”
    • swrve.managedModeAutoStartLastUser is “false”
  • Push notification engaged events are always tracked against the last known user ID (even if InitMode is MANAGED and ManagedModeAutoStartLastUser is false).
  • Use the SwrveSDK.IsStarted() API to check if the SDK is started before calling regular APIs when initMode is MANAGED and ManagedModeAutoStartLastUser is false.

Manage how you track user behavior

Swrve provides the identify API to help you manage how you track user activity across app sessions and multiple devices. For more information on how to identify users and then track and target them safely across multiple devices, platforms, and channels, see Tracking your users with Swrve User Identity.

External user ID

The external user ID is a non-discoverable key that identifies your user across multiple channels and platforms. To ensure app security, Swrve does not accept email or other personally identifiable information (PIIs) as the external user ID and rejects them on the server side. Before you implement the Identify service, please consult with your CSM at support@swrve.com for some guidance on best practices to follow in your integration.

The external user ID should always be unique to each user. Using a shared external user ID across users may have adverse consequences on user segmentation, reporting, audiences, and QA device behavior.

Identify pre-existing users

To find pre-existing user identities that an app has logged, either on a single device or multiple devices, when you are ready, call the identify API with your external user ID:

window.plugins.swrve.identify(
        "<external_user_id>",
	    function(response) {/** Success, continue with your logic */},
        function(response) {/** Error, should be handled  */}
);

If the call fails, the user’s activity is not linked to an existing user ID in Swrve’s backend system, which might affect reporting and audiences where the user is logging in on multiple devices. We recommend not queuing or sending events until the identify call completes.


Push notifications

Use Swrve’s push notification campaigns to send personalized messages to your app users while they’re outside of your app or send silent background app updates. For more information, see Intro to push notifications.

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

Step 1: Modify the config.xml at the root of your Cordova/PhoneGap project.

iOS

  • Ensure the swrve.pushEnabled preference is present and set to true. This uses a hook system to generate a Service Extension for rich media and push delivery tracking capabilities.
  • To track push delivery and users who are influenced by a push notification, the swrve.appGroupIdentifier preference is required. For more information on how we track push delivery and influenced users, see the iOS integration guide. You must complete the additional required steps in the Apple Developer portal.
  • We do not handle signing and capabilities for the main target, so you need to open the generated Xcode project and enable the Push Notification Capability. If you also decide to use App Groups, you need to enable that capability as well. Finally, ensure that your team and app provisioning is set for both the service extension and main target. For more information on Capabilities please refer to Step 4 of Adding a service extension in our iOS Integration Guide.
  • Swrve iOS service extensions utilize a cocoapods target to import the relevant dependencies. If there are build issues when first installing the plugin with push. you may need to perform a pod install command from the platform/ios directory of your application.
<platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
    <preference name="swrve.appId" value="<swrve_app_id>" />
    <preference name="swrve.apiKey" value="<swrve_api_key>" />
    <preference name="swrve.pushEnabled" value="true" />
    <preference name="swrve.appGroupIdentifier" value="group.com.example.hello" />
</platform>

Android

  • Ensure the swrve.pushEnabled preference is present and set to true. This uses a hook system to add all changes to the Manifest.xml file and to add the appropriate code.
  • Android push notifications require you to specify the images that appear in the status bar on receiving a notification. Swrve requires two images with specific names. material_icon.png is the icon that appears in the status bar for devices running Android API levels greater than 20 and icon.png  is for Android devices below API level 21. Add both images to a folder at the root of your project and include the path to the directory under the swrve.drawablePath preference.
  • The SwrveSDK uses Firebase Cloud Messaging for push notifications. This requires the google-services.json file that is located at the root of the module, which is provided by the SwrvePlugin through a hook script. You must provide a path from swrve.googleServicesPath to your google-services.json, and set the GradlePluginGoogleServicesEnabled preference to true.
<platform name="android">
    <allow-intent href="market:*" />
    <preference name="GradlePluginGoogleServicesEnabled" value="true" />
    <preference name="swrve.appId" value="<swrve_app_id>" />
    <preference name="swrve.apiKey" value="<swrve_api_key>" />
    <preference name="swrve.pushEnabled" value="true" />
    <preference name="swrve.drawablePath" value="file_at_root_of_project/android/drawable/" />
    <preference name="swrve.googleServicesPath" value="file_at_root_of_project/android/google-services.json" />
</platform>

Step 2: If you want to perform custom processing of the push notification engagement payload, you can add a listener on the JavaScript layer that will return the payload of a notification when it is engaged with:

window.plugins.swrve.setPushNotificationListener(function(payload) { 
  // Do something with the push payload 
});

Step 3: If you have already generated a platform, use remove and add commands to regenerate your platforms and add the changes included in your push notification hooks.

cordova platform remove android
cordova platform remove ios

cordova platform add android@11.0.0
cordova platform add ios

iOS provisional authorization for push

In iOS 12, Apple added a feature for provisional authorization of push notifications. This feature enables you to send push notifications as soon as a user opens your app for the first time, without requiring the user to opt-in. The notification is delivered directly to the device’s Notification Center and when the user views the notification, the message automatically includes a built-in prompt asking if they want to continue to receive notifications.

By default, the Swrve SDK requests full push permission the first time the user launches your app. To implement provisional authorization for iOS, set different events for both the provisional and full authorization in the iOS platform of your config.xml.

<preference name="swrve.pushNotificationEvent" value="<your_push_enable_event_name>" />
<preference name="swrve.provisionalPushNotificationEvent" value="<your_provisional_push_enable_event_name>" />

Configuring iOS silent notifications

The purpose of a silent notification is to refresh your app’s data when it is running in background, for example, a content update. You should never call the SDK from a silent notification. Note, iOS does not permit silent notifications to wake up the app if it is completely closed (that is, a user has double-clicked the home button and swiped up to close the app). If the app is closed, you can only update the badge number.

To enable silent push notifications in your app, complete the following:

Step 1: Early in your application config, include a listener for silent notifications.

window.plugins.swrve.setSilentPushNotificationListener(function(payload) {
   // Do something with the silent push payload 
});

Step 2: Modify the Info.plist of the Xcode project that is generated in platforms. You can do this by adding the following addition to the iOS platform in your config.xml file.

<platform name="ios">
    <edit-config target="UIBackgroundModes" file="*-Info.plist" mode="merge">
        <array>
           <string>remote-notification</string>
        </array>
    </edit-config>
</platform>

Android notification permission

A feature has been introduced by Google for Android 13, whereby users must actively grant permission for an app to display notifications on their device. For more information, see Push notification permission request.

By default, the Swrve SDK will not request the push notification permission prompt. To trigger the prompt via an event, set the event name for Android in your config.xml.



In-app messages and Conversations

Swrve’s in-app messages and Conversations campaigns are available as soon as you complete the basic integration described above. 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.

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.

 

 

        • Android – Custom URL schemes are defined in your AndroidManifest.xml

       

       

 

 

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 an in-app message. Use the following callback:

window.plugins.swrve.setCustomButtonListener(function(action) { 
  // Do something with the action
});

Embedded campaigns

Swrve’s embedded campaigns give you complete control over how you deliver, handle, and display content on your app, while still letting you use our powerful audience targeting and event triggering system to deliver the campaign. This opens up scenarios where you can deliver JSON to your application, targeted to specific users, triggered by specific situations, like a campaign, and then use this JSON to custom render a visual in your own application code. For more information see Embedded experiences. To implement embedded campaigns in your integration, you need to register for the embedded callback early in your application code. For example:

window.plugins.swrve.setEmbeddedMessageCallback(function(messageData)) {
   // Do something with the callback
});

 

To use Swrve’s tracking, there are methods you can call within the SwrveEmbeddedMessage listener. Use these methods to send impression and click events for your own embedded campaigns and make use of Swrve’s targeting, segmentation, and goal tracking. For example:

window.plugins.swrve.setEmbeddedMessageCallback(function(messageData)) {
   // parse the messageData object, which includes data, campaignId, messageId 
   // and the personalization properties associated with it. 
   var embeddedCampaign = JSON.parse(messageData);

   // If you want to track an impression event
   window.embeddedMessageWasShownToUser(embeddedCampaign.message.campaignID, null /**success callback**/, null /** failure callback **/);

  // The message object returns a list of strings representing the button options. 
  // In this example we are taking out the first button from the list and sending a click event window.
  window.plugins.swrve.embeddedMessageButtonWasPressed(embeddedCampaign.message.campaignID, embeddedCampaign.message.buttons[0], null /**success callback **/, null /**failure callback **/);
});

Embedded campaign personalization

As of Swrve Plugin 4.0.0, we provide built-in personalization support for embedded campaigns. Personalization in any kind of triggered campaign uses a set of custom properties you’ve implemented in your app and then configured for realtime personalization in Swrve. For information about configuring these properties, see Manage user properties or contact your CSM at support@swrve.com. Once configured, the properties are immediately available for use in your embedded campaigns.

The Swrve SDK has direct access to the most recent version of the realtime user properties values in Swrve. When your app makes an embedded campaign callback, the contents of the personalizationProperties argument in the embedded message include the realtime user properties retrieved during the process of triggering the campaign.

Since the format of embedded campaigns depends on how you configured your app (for example, you might use JSON, XML, plain text), Swrve does not parse and process your embedded campaign content. Although the campaign editor lets you select realtime properties for personalization, it is your responsibility to inject the properties as part of your embedded campaign integration. To help make this process easier for you, we have provided the getPersonalizedEmbeddedMessageData API.

window.plugins.swrve.setEmbeddedMessageCallback(function(messageData)) { 
   // parse the messageData object, which includes data, campaignId, messageId 
   // and the personalization properties associated with it. 
   var embeddedCampaign = JSON.parse(messageData); 
   
   // In this case, we are taking the personalizationProperties provided from the parsed messageData.
   window.plugins.swrve.getPersonalizedEmbeddedMessageData(embeddedCampaign.message.campaignID,
                                                           embeddedCampaign.personalizationProperties,
                                                           function(response){
                                                               alert(response); /** successful response **/
                                                           },
                                                                null /** failure response **/
                                                           );

});

Sending events

The Swrve SDK automatically sends certain events and also enables you to track user behavior by sending custom 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.

window.plugins.swrve.event(
  "custom.event_name",
  undefined,
  successCallback,
  failureCallback);

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 and for audience filtering.
  • If you want to use event payloads to target your campaign audiences, you can configure up to 10 custom events with a maximum of 20 payloads per event for audience filtering purposes. For more information, see Targeting your audience by event payloads.
window.plugins.swrve.event(
  "custom.event_name",
  {
    "key1":"value1",
    "key2":"value2"
  },
  successCallback,
  failureCallback
);

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.

window.plugins.swrve.event(
  "tutorial.start",
  {
    "time":"100",
    "step":"5"
  },
  successCallback,
  failureCallback
);

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.

window.plugins.swrve.userUpdate(
  {
    "premium": "true",
    "level": 12,
    "balance": 999
  },
  successCallback,
  failureCallback
);

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.

window.plugins.swrve.purchase(
  "some.item",
  "gold",
  1,
  99,
  successCallback,
  failureCallback
);

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

window.plugins.swrve.currencyGiven(
  "gold", 
  50,
  successCallback,
  failureCallback
);

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.

Unvalidated IAP

Due to the nature in which Cordova uses a shared JavaScript, we cannot provide an SKReceipt or Google Play response in a JavaScript way. It is available natively, which is covered in the iOS and Android integration guides. However, if you want to simply build revenue reports for your app but do not have or want the receipt to be validated by our servers, use the following unvalidatedIap function:

window.plugins.swrve.unvalidatedIap(
   99.5,
   'USD',
   'IAP_TEST_ID',
    1,
    successCallback, 
    failureCallback
 );

With your IAPs, you can also track rewards provided for the IAP. This could be something like in-game currency or access to a premium service. These are provided as an optional JSON object that is made up of two JSON lists. One is for items received and the other is related to a virtual currency that you have registered in your Swrve dashboard. The below example includes one of each:

window.plugins.swrve.unvalidatedIapWithReward(
  10, 
  "USD", 
  "item_sku", 
  1, 
  { items: [ { name: 'test.itemname', amount: 2 } ], currencies: [ { name: 'Gold', amount: 200 } ] },
  successCallback, 
  failureCallback
);

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, use the following:

// Get the latest resources
window.plugins.swrve.getUserResources(function(resources) {
  // JSON object containing the resources
  alert(resources.welcome_string);
} function () {
  alert("Error: could not get resources");
});

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

window.plugins.setResourcesListener(function(resources) {
  // Do something with the new resources
});

Troubleshooting

Since this SDK is build primarily for the Cordova CLI, we run the majority of our tests against that tool. Ionic and PhoneGap are still tested internally to help increase overall compatibility. This section provides workarounds for known issues with those platforms.

PhoneGap

When adding the android platform to your PhoneGap project, the PhoneGap CLI selects android-cordova 7.1.1 that targets Android 27. Our Plugin uses an Android SDK that targets 28 and therefore may cause Gradle build issues. To ensure this doesn’t happen, please use the following steps:

Step 1: Once the Android platform is generated, open the project.properties file inside: platform/android/project.properties.

Step 2: Replace the target value from android-27 to android-28 and re-sync your Gradle build. It should now build.


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 Cordova SDK to the current version, see the Cordova SDK upgrade guide for upgrade instructions.