Last modified February 12, 2024 by Shelly Wolfe

React Native

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

The Swrve React Native 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 React Native plugin uses the native SDKs for iOS and Android. You can find more information about the native SDKs in the platform-specific documentation.
  • A recent version of NPM and Yarn
  • A recent version of CocoaPods and Gradle
  • The React Native CLI and environment setup

Installing the SDK

Swrve’s SDK repository is open source. Installing the SDK from NPM is mostly automatic:

$ npm install react-native-swrve-plugin --save

If you prefer to use Yarn, run the following command:

$ yarn add react-native-swrve-plugin

Adding the SDK to your project

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

Step 1: iOS uses CocoaPods for getting the Swrve native iOS SDK. To ensure you have the correct dependencies available, go to ios/ in your project and run:

pod install && pod update

Step 2: In your AppDelegate.m or AppDelegate.mm file, import the Swrve SDK and the plugin at the top of the file:

#import <SwrveSDK/SwrveSDK.h>
#import "SwrvePlugin.h"

Step 3: In application: didFinishLaunchingWithOptions:, initialize the SDK with your configuration:

SwrveConfig* config = [[SwrveConfig alloc] init]; 
// To use the EU stack, include this in your config
// config.stack = SWRVE_STACK_EU;
[SwrvePlugin initWithAppID: <swrve_app_id> apiKey:@"<swrve_api_key>" config:config];

Android

Step 1: In your MainApplication.java file, import the Swrve SDK and the plugin at the top of the file:

import com.swrve.reactnative.SwrvePlugin;
import com.swrve.sdk.config.SwrveConfig;
import com.swrve.sdk.config.SwrveStack;

Step 2: Update your OnCreate() method to intialize the plugin and SDK:

SwrveConfig swrveConfig = new SwrveConfig();
// To use the EU stack, include this in your config
// swrveConfig.setSelectedStack(SwrveStack.EU);
SwrvePlugin.createInstance(this, <swrve_app_id>, "<swrve_api_key>", swrveConfig);

Once the native code has been added you can import the SwrveSDK for use in your React code:

import SwrveSDK from 'react-native-swrve-plugin';

Manage how you track user behavior

Swrve provides the following APIs to help you manage how you track user activity across app sessions and multiple devices.

  • Identify – Makes a call to Swrve to determine if the current user has an existing Swrve user ID, by checking to see if the external user ID they provide is already linked to a known user ID in Swrve.
  • Stop tracking – Stops all tracking of the current user’s activity. After this call is made, the SDK runs silently in the background and does not track user activity again until you call the identify or start API.
  • Start – Resumes tracking user activity after you call the stopTracking API.

This section explains how to use these APIs to manage how you track anonymous users, known users (that is, a user logs in and the SDK identifies them based on an external user ID), and users for whom you want to stop tracking activity (for example, a user logs out). 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

Use the identify API to find pre-existing user identities that an app has logged, either on a single device or multiple devices. To use the identify API, initialize the Swrve SDK as normal in your application:

try {
    let ident = await SwrveSDK.identify(userIdentity);
    alert(`Identify successful - ident ${ident}`);
} catch (e) {
    alert(`Identify failed - ${e}`);
    console.log('Identify failed', e);
}

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.

Delay tracking activity until user is identified

By default, once the SDK initializes it automatically starts tracking user activity. If you use the identify API on its own, when a user first installs the app, Swrve tracks any activity that takes place prior to calling the identify API as anonymous. For subsequent sessions, it attributes activity to the last known user.

To delay tracking until you’ve identified the user, use the autoStartLastUser configuration property. If you set autoStartLastUser to false, the SDK does not start tracking any activity until you identify the user. Use this option if you do not want to track any anonymous user activity. For React Native, you must add the property in the native layer in two places:

iOS

In your AppDelegate.m file, under application: didFinishLaunchingWithOptions:, add the following property to your Swrve config changes before the Swrve init code:

config.autoStartLastUser = NO;

Android

In the onCreate() method, add the following property to Swrve config changes before the Swrve init code:

swrveConfig.setAutoStartLastUser(false);

If you set the autoStartLastUser configuration property to false, the SDK:

  • Only tracks user activity once you call the identify API.
  • Does not automatically start tracking user activity if the app cannot call the stopTracking API for some reason (for example, if the user hard-closes the app before the stopTracking API call is complete).
  • Does not display in-app message campaigns that are linked to a push notification.
  • Attributes push notification engagement metrics to the last user the SDK was tracking.

To check if the SDK is started before calling regular APIs when autoStartLastUser is false, use the SwrveSDK.isStarted() API.

Stop tracking user activity

As of React Native Plugin version 2.0.0, it is possible to stop the SDK from tracking user activity and logging events. To stop tracking the current user’s activity, call the stopTracking API:

SwrveSDK.stopTracking()

After you call the stopTracking API, the SDK:

  • Disables most APIs and returns empty strings or null objects as defaults.
  • Does not start tracking user behavior again until you call the start or identify API.
  • Continues to display push notifications, except those you restrict to display only for identified users. The SDK attributes engagement metrics to the last user the SDK was tracking.
  • Does not display in-app message campaigns, including those that are linked to a push notification.
  • Continues to process background app updates.

Resume tracking user activity

To resume tracking after you call the stopTracking API, call the start or identify API:

SwrveSDK.start()

If you call the start API, by default the SDK resumes tracking against the last known user ID. If you don’t want to assume it’s the same user, call the identify API.

Custom Swrve user ID

If your integration uses a custom Swrve user ID, there are additional steps you need to take to manage the SDK intitialization and user activity tracking. For more information, contact your CSM at support@swrve.com.


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.

Swrve’s React Native plugin leverages the native Swrve SDKs, so the majority of the push notification setup is done in the native code for those apps. The tabs below provide links to the native SDK instructions for configuring push notifications and highlight any key differences that are required to run with the React Native plugin.

iOS

To use Swrve’s push notification registration, processing, and tracking services, you first need to enable push as part of the config you have added to appDelegate.m.

Step 1: In your application: didFinishLaunchingWithOptions:, enable push notifications:

config.pushEnabled = YES;

Step 2: To track push delivery and users who are influenced by a push notification, you must set up both a Service Extension and have the application configured for App Groups . For more information on how we track push delivery and influenced users, see the iOS integration guide. Complete the additional required steps in the Apple Developer portal.

Step 3: Once completed, in your application: didFinishLaunchingWithOptions:, ensure your app group identifier is set in your config as part of the code:

config.appGroupIdentifier = @"group.com.example.swrve";

Note: The iOS Integration guide explains how to add a pushDelegate to your config. This is not needed as part of the React Native setup as we handle it in the plugin.

Step 4: In the same appDelegate.m file, the native iOS integration requires you include functions for three situations:

  • The app is launched from a push notification.
  • The app receives a push notification while running.
  • The app receives a deeplink from a push notification.

The code sample is very similar for React Native, with the addition of a SwrvePlugin call that you need to include as part of the openURL:

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
  [SwrvePlugin handleDeeplink:url]; // this is the additional code that needs to be added
  return [RCTLinkingManager application:app openURL:url options:options];
}

Android

Update your Manifest.xml file, Gradle files, and SwrveConfig in MainApplication.java as specified in the Android integration guide.

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 as part of the SwrveConfig in the AppDelegate.m file.

config.pushNotificationEvents = [NSSet setWithObject:@"full_permission_button_clicked"];
config.provisionalPushNotificationEvents = [NSSet setWithObject:@"Swrve.session.start"]; // Ask for provisional push permission on app launch

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 notifications in your app please see Configuring silent notifications in the iOS integration guide.

Listening for push payloads

If you want to perform custom processing of the push notification engagement payload, you can add a listener on the React JS layer that returns the payload of a notification when a user engages with it:

SwrveSDK.setListeners()

constructor(props) {
    super(props);

    SwrveSDK.setListeners(
        /** Swrve UserResourcesListener arg **/ null,
        {pushListener: onPushMessage, silentPushListener: onSilentPushMessage}
    );
}

const onPushMessage = async (payload) => {
    console.log("onPushMessage", payload);
}

const onSilentPushMessage = async (payload) => {
    console.log("onSilentPushMessage", payload)
}

Notifications received before the React Native framework has started are received by the Swrve plugin and buffered until the first listener is attached. There is no need to call getInitialNotification() or similar to deal with notifications during startup.

Working with deeplinks

The Swrve React Native SDK integrates directly with the React Native Linking functionality so you can work with notification URLs in the standard way. To register for notifications, you need to add code to one of your main components:

async componentDidMount() {
    let url = await Linking.getInitialURL();

    if (url) {
        console.log("got initial URL", url);
        await this.handleOpenURL(url);

    }

    Linking.addEventListener("url", (event) => {
        console.log("Url event listener", event);
        this.handleOpenURL(event.url);
    })
}

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.

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 listener interactions

As of React SDK 5.0.0, the following callback listeners are removed:

  • MessageCustomButtonPressedListener
  • MessageDismissButtonPressedListener
  • MessageClipBoardButtonPressedListener

The new InAppMessageListener now receives callbacks for the following in-app message interactions:

  • In-app message impression
  • Custom button action
  • Dismiss button action
  • Copy to clipboard button action

The InAppMessageListener may be called multiple times, such as for the initial impression and subsequent button actions like Dismiss, Custom, or CopyToClipboard. It is important to manage each case in the callback logic.  If a deeplink is present on a custom action or from a push message, the SwrveSDK will attempt to open the deeplink. To override this behaviour, implement the DeeplinkListener.

constructor(props) { 
  super(props); 
    SwrveSDK.setDeeplinkListener(
      {deeplinkListener: onDeeplinkListener}
    );
} 

const onDeeplinkListener = async (actionString) => {
     Linking.openURL(actionString);
};

To receive added in-app message interactions, implement the InAppMessageListener like this:

constructor(props) { 
  super(props); 
  SwrveSDK.setInAppMessageListener(
    {inAppMessageListener: onMessageDetails}
  );
} 

const onMessageDetails = async (messageAction, messageDetails, selectedButton) => {
  
    switch (messageAction) {
        case 'Impression':
            // process impression callback
            break;
        case 'Custom':
            // process custom button action callback
            // SwrveSDK will handle deeplinks internally
            // To override this behavior, you can implement the DeeplinkListener
            break;
        case 'Dismiss':
            // process dismiss button action callback
            break;
        case 'Clipboard':
            // process copy to clipboard button action callback
            break;
        default:
            break;
    }
};

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 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.

To implement embedded campaigns in your integration, pass your own listener to the EmbeddedCampaignListener. To use Swrve’s tracking, holdout groups, and personalization, there are methods you can call within the EmbeddedCampaignListener. Use these methods to send impression and click events for your own embedded campaigns and use Swrve’s targeting, segmentation, and goal tracking. For example:

constructor(props) {
    super(props);
    SwrveSDK.setEmbeddedCampaignListener({
        embeddedCampaignListener: onEmbeddedMessageWithControl
    });
}

const onEmbeddedMessageWithControl = async (message, personalizationProperties, isControl) => {
    if (isControl) {
        // this campaign should not be shown to user, to help with 
        // reporting you should use the api below to send us an impression event
        SwrveSDK.embeddedControlMessageImpressionEvent(message.campaignId)
    } else {
        SwrveSDK.markEmbeddedMessageCampaignAsSeen(message.campaignId);
        // retrieve the first button from the embedded campaign for demonstration purposes
        const buttonName = message.buttons[0];
        SwrveSDK.markEmbeddedMessageButtonAsPressed(message.campaignId, buttonName);
    } 
}

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.

SwrveSDK.event("event_name");

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.
SwrveSDK.event("event_name", {referrer: "reference_name", current_level: 3});

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.

SwrveSDK.event("tutorial.start", {time: 100, step: 5});

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.

SwrveSDK.userUpdate({
    "premium": "true",
    "level": 12,
    "balance": 999
  });

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.

SwrveSDK.purchase("some.item", "gold", 1, 99);

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

SwrveSDK.currencyGiven("gold", 50);

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 React 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:

SwrveSDK.unvalidatedIap(99, "USD", "IAP_TEST_ID", 1);

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:

SwrveSDK.unvalidatedIapWithReward(10, "USD", "item_sku", 1,
{
    items: [
        { name: "item.testname", amount: 2 }
    ],
    currencies: [
        { name: "Gold", amount: 200}
    ]
});

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 the user resources from Swrve, use the following:

var resources = await SwrveSDK.getUserResources();

If you want to be notified whenever resources change, you can register a callback to listen for changes. It is recommended to do this as part of the constructor in the App.js or whichever class extends React.component first.

constructor(props) {
    super(props);

    SwrveSDK.setListeners(
        { userResourcesUpdatedListener: onResourcesUpdated },
        /** Push listeners arg **/ null,
        /** in-app listeners arg **/ null,
        /** embedded listener arg **/ null
    );
}

// in the same file
const onResourcesUpdated = async () => {
    console.log('resources have updated');
    // Act on the resources being updated
};

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