Help Center

BlueConic SDK for React Native

How to use the BlueConic SDK for React Native to develop custom CDP mobile applicationsThe BlueConic SDK for React Native makes it easy for developers to collect profile data from their Android and/or iOS native apps. This article explains how to integrate BlueConic into your React Native apps. If you are looking for details on Android apps, see the BlueConic SDK for Android, and, for details on iOS apps, see the BlueConic SDK for iOS.

You can use the React Native SDK to do the following:

  • Set and retrieve profile property values
  • Serve (custom) dialogues 
  • Track user behavior using listeners

The BlueConicClient Framework provides the basis for communication with BlueConic. It provides possibilities to develop your own interactions by creating mobile plugins. BlueConicClient Framework allows you to make use of the standard BlueConic plugins. It contains several plugins that are mobile variants of the standard BlueConic Listeners plugins.  


Before you begin

Before you start implementing the SDK, make sure you have the following:

  • Android: The minimum SDK version supported by the SDK is 21. Make sure that your app is compatible with this.
  • iOS: The latest version of Xcode (v14.3.1 or higher).
  • iOS: The binary distribution files of the SDK have been built for iOS 12.

Getting Started

Note

The latest SDK version is 4.0.0 using Android version 6.0.0 and iOS version 4.0.0.

Before you start implementing the SDK, use the following steps to set up your environment:

React Native

Run the following command in your React Native project's root folder:

$ npm install @blueconic/blueconic-react-native

Or include it in your React Native project's package.json:

{
"react": "*",
"react-native": "*",
"@blueconic/blueconic-react-native": "<latest version>"

}
  1. Import NativeModules into the app

    Import the BlueConicClient module within your app:

    import { NativeModules } from "react-native";
    const {BlueConicClient} = NativeModules;
  2. Initialize the SDK
    The Android SDK should be configured using a BlueConicConfiguration object and a builder class in the Application class. The BlueConic SDK should be initialized before any other SDK API calls are made.
    import { BlueConicConfiguration } from '@blueconic/blueconic-react-native';
    
    const configuration = new BlueConicConfiguration.Builder() 
        .setHostName([BlueConic server url]) // Replace with hostname of the BlueConic server 
        .setOverrideAppId(overrideAppId) // Set this only if you need your app ID to be different than your package name 
        .build(); 
    
    BlueConicClient.initialize(configuration, async (success: boolean, error: string) = { 
        if (success) { 
            console.log('BlueConicClient initialized'); 
        } else { 
            console.error('BlueConicClient initialization failed: ' + error); 
        } 
    });

iOS implementation of the React Native App

Note

For the iOS 17 privacy changes that apply to SDK, check the information provided here: BlueConic SDK for iOS.

Note

The iOS SDK used by React is distributed via Cocoapods.

If you are using React Native CLI, make sure you have the pods installed by the following command:

pod install

Android implementation of the React Native App

Note

The Android SDK used by React is distributed via Gradle dependency.

Set up Proguard
If you're using Proguard to optimize and minify your app, you must add the following rules to prevent Proguard from removing the SDK:

-keep class com.blueconic.** { *; }

Using the BlueConicClient SDK in React Native apps

Understanding Callback information

Almost all SDK API methods allow for an optional Callback interface to be passed at the method invocation point to receive information from the SDK about whether the operation was successful or failed. The structure of the interface is as follows:

async (success: boolean, error: string) = { 
    if (success) { 
        // The API operation was successful 
    } else { 
        // The error for the API operation 
    }  
}

The Error object contains the following error types that the SDK can trigger:

NotEnabled
AlreadyEnabled
InteractionRetrievalError
InvalidParameters
InternalError
UnsupportedAndroidAPI

Create a page view event

To keep track of every page viewed in the app, you need to create a page view event. Make sure that a unique screen name is passed in the call. The screen name can be used in listener rules or to restrict interactions to specific screens. 

// Simple screen names, like 'main' pages
BlueConicClient.createPageViewEvent("main", {});
  
// With promise
await BlueConicClient.createPageViewEventAsync("main", {});

// With callback
BlueConicClient.createPageViewEventWithCallback("main", {}, async (success: boolean, error: string) = {
    if (success) { 
        // The API operation was successful 
    } else { 
        // The error for the API operation 
    } 
});

The "screenName" property sent via a PAGEVIEW event is used by BlueConic to identify the location in the app.

Now the BlueConic user can retrieve the screen name "Main/Section1" as a value like so (using the regular expression (.*)):

Or the BlueConic user can add values when the Mobile Screen name contains certain words. Create a rule of type "URL / Mobile Screen" and configure the Mobile Screen name to listen to:

Configure consent

To configure the consent information for the BlueConic SDK you can use the following methods:

// Get the SDK privacy legislation.
// With promise 
const privacyLegislation = await BlueConicClient.getPrivacyLegislationAsync(); 
// With callback 
BlueConicClient.getPrivacyLegislationWithCallback(privacyLegislation => {}); 

// Get the SDK objectives.
// With promise 
const consentedObjectives = await BlueConicClient.getConsentedObjectivesAsync(); 
// With callback 
BlueConicClient.getConsentedObjectivesWithCallback(consentedObjectives => {});
// With promise 
const refusedObjectives = await BlueConicClient.getRefusedObjectivesAsync(); 
// With callback 
BlueConicClient.getRefusedObjectivesWithCallback(refusedObjectives => {});
  
// Configure the SDK privacy legislation (e.g. GDPR, CCPA).
BlueConicClient.setPrivacyLegislation("GDPR"); 
  
// Add consented objective.
// First, the objectives need to be configured in the BlueConic platform. 
BlueConicClient.addConsentedObjective("Marketing")
  
// Add refused objective. 
// First, the objectives need to be configured in the BlueConic platform. 
BlueConicClient.addRefusedObjective("Tracking")

To configure consent information in BlueConic read more about it in the following article: Privacy management in BlueConic.

Create a timeline event

The BlueConic SDK supports the ability to send timeline events using the following dedicated methods:

// Set the properties of the timeline event.
let properties = {
    propertyKey: "propertyValue",
    propertyNestedMap: {
        nestedKey: "nestedValue",
        nestedKey2: 123, 
        nestedKey3: true 
    } 
};

// Trigger the timeline event.
// Note that when using this method, the ID of the timeline event will be an automatically generated UUID.
BlueConicClient.createTimelineEvent("MY_TIMELINE_EVENT", new Date().getTime(), properties);
// With promise 
await BlueConicClient.createTimelineEventAsync("MY_TIMELINE_EVENT", new Date().getTime(), properties); 
// With callback 
BlueConicClient.createTimelineEventWithCallback("MY_TIMELINE_EVENT", new Date().getTime(), properties, async (success: boolean, error: string) = {
    if (success) { 
        // The API operation was successful 
    } else { 
        // The error for the API operation 
    } 
});
  
// Trigger the timeline event by ID.
BlueConicClient.createTimelineEventById("MY_TIMELINE_ID", "MY_TIMELINE_EVENT", new Date().getTime(), properties);
// With promise 
await BlueConicClient.createTimelineEventByIdAsync("MY_TIMELINE_ID", "MY_TIMELINE_EVENT", new Date().getTime(), properties); 
// With callback 
BlueConicClient.createTimelineEventByIdWithCallback("MY_TIMELINE_ID", "MY_TIMELINE_EVENT", new Date().getTime(), properties, async (success: boolean, error: string) = {
    if (success) { 
        // The API operation was successful 
    } else { 
        // The error for the API operation 
    } 
});

To learn more about timeline events and how to configure them in BlueConic, check out the following article: Overview: Timeline events in BlueConic.

Clean up BlueConic interactions 

Creating a page view event will dynamically load interactions (dialogues and listeners) in the app. It is necessary to explicitly call 'destroyPlugins' on the BlueConicClient when the user switches screens.

BlueConicClient.destroyPlugins();

Gather Profile information

When you first interact with BlueConic using the SDK, a profile ID is generated. This profile ID can be used to identify users in BlueConic. To retrieve the BlueConic assigned profile ID, you can use the following method:

// With promise 
const profileId = await BlueConicClient.getProfileIdAsync();

// With callback
BlueConicClient.getProfileIdWithCallback(profileId => {
});

The BlueConic SDK supports the ability to get or set a profile property directly from inside the app. Ask your BlueConic users for the ID of the profile property in BlueConic and use one or more of the following BlueConic methods from the SDK:

// Get profile property value
// With promise
const hobby = await BlueConicClient.getProfileValueAsync("propertyKey"); 
// With callback
BlueConicClient.getProfileValueWithCallback("propertyKey", value => {}); 
  
// Get profile property values (for multi-value properties)
// With promise
const hobbies = await BlueConicClient.getProfileValuesAsync("propertyKey");
// With callback
BlueConicClient.getProfileValuesWithCallback("propertyKey", value => {});
  
// Set profile property value.
// Passing a property that was already set with values will cause for the old values to be removed. 
BlueConicClient.setProfileValue("propertyKey", "propertyValue"); 
  
// Set profile property values (for multi-value properties).
// Passing a property that was already set with values will cause for the old values to be removed. 
BlueConicClient.setProfileValues("propertyKey", ["propertyValue1", "propertyValue2"]);
  
// Add profile property value.
// If there are already values for a property the new value will be added.
BlueConicClient.addProfileValue("propertyKey", "propertyValue");  
  
// Add profile property values (for multi-value properties).
// If there are already values for a property the new values will be added.
BlueConicClient.addProfileValues("propertyKey", ["propertyValue1", "propertyValue2"]);
  
// Increment profile property value.
// If there are already values for a property the new value will be the sum of all values.
BlueConicClient.incrementProfileValue("propertyKey", "1");  
  
// Update the profile to sync over the data from the.
// Mobile app to the BlueConic servers and also pull in the data that has changed on the BlueConic side.
BlueConicClient.updateProfile();
// With promise 
await BlueConicClient.updateProfileAsync(); 
// With callback 
BlueConicClient.updateProfileWithCallback(async (success: boolean, error: string) = {
    if (success) { 
        // The API operation was successful 
    } else { 
        // The error for the API operation 
    } 
});

A common use case for setting profile properties directly is to store attributes of the user, especially those that can be used for profile merging across devices. To do this, you first need to note the ID of the user and email address profile properties you wish to populate (e.g. user_id and email). Then, the setProfileValue method should be used to populate these profile properties accordingly.

If you require your Profile ID to be reset locally on the device, you can use the following method:

BlueConicClient.clearProfileId(async (success: boolean, error: string) = {
    if (success) { 
        // The API operation was successful 
    } else { 
        // The error for the API operation 
    } 
});

Publish Events

The BlueConic SDK allows you to send events to BlueConic. This allows you to keep BlueConic informed of what is happening in your app, even when it happens outside the scope of the basic operations.

Events are sent using the BlueConic's publish() function. Several kinds of events can be published:

ClickEvent
This event signals to BlueConic that a component with a specific ID has been clicked in your app.
UpdateContentEvent
This event signals to BlueConic that the content of a component with a specific ID has updated its content and also passes on the updated content.
UpdateValuesEvent
This event signals to BlueConic that a component with a specific ID has received an updated list of values and passes on these updated values.
FormSubmitEvent
This event signals to BlueConic that the form with a specific ID has been submitted.
AdvancedEvent
This allows you to send a custom event to BlueConic with its own specific name and a list of values.

Click event

BlueConic enables users to indicate the button that defines the click area in a Click / Tap rule as follows:

To make this work for your BlueConic users, add the following code to your app:

// Define click event for selector "#nextButton"
BlueConicClient.publishClickEvent("#nextButton", []);

Updating content

BlueConic enables you to detect words on the mobile screen:

The BlueConic SDK will scan the mobile screen upon loading the view for the first time. But what if you change the contents of the screen without reloading the view?

To enable this for the BlueConic users at your site, publish an UpdateContentEvent. Add the following code to your app:

// Define update content event for selector "#emailAddress"
BlueConicClient.publishUpdateContentEvent("#emailAddress", "test@test.com");

Updating values

BlueConic enables you to create a form listening rule that updates a profile property when a form field changes its value:

"TextView" and "Spinner" widgets will automatically pick up value changes. All other field types have to be facilitated within your app code.

To make this work for your BlueConic users for non-supported fields, add the following code to your app:

// Define update values event for selector "#emailAddress"
BlueConicClient.publishUpdateContentEvent("#emailAddress", "test@test.com");

Now, when the user enters an email address in your app, it will be picked up in BlueConic as well.

Form submit

BlueConic enables you to listen to in-app form submits as follows:

To enable this for your BlueConic users, add the following code to your app:

// Define form submit event for selector "#loginForm"
BlueConicClient.publishFormSubmitEvent("#loginForm", ["value"]);

Custom-defined event

BlueConic enables you to set profile property values when a custom-defined event is received. It even allows you to check for specific values in the context of the event:

To enable this feature for your BlueConic profiles, add the following code to your app:

// Define advanced event with the name "video_started"
BlueConicClient.publishAdvancedEvent("video_started", ["blueberry", "sushi", "pancakes"]);

The app publishes an event with the name "video_started" and a list of three values ("blueberry," "sushi," and "pancakes") is added as context. Adding values is optional; it provides extra information to allow BlueConic users at your site to make more specific rules.

On the BlueConic side, the example rule in the screenshot says "... if event video_started is received with a context that contains blueberry, raspberry for any value." The published example event contains one of those values (blueberry) for the event, which means there is a match. As a result, BlueConic will add the value "fruit" to the profile property "Food Preferences" of the profile for this particular app user.

Adding context

Adding context to an event makes it a lot easier to develop and configure which values a mobile developer can use and send through the event to BlueConic, where the event context can be used with BlueConic Listeners. Previously, this had to be configured by using a public UI element to retrieve data from a mobile app. Now mobile developers can use private or dynamic values and apply them directly as context to an event. This gives you more control and flexibility to publish BlueConic events within an app, and the BlueConic users at your site can use them to define BlueConic Listeners, without having to know about the internal UI IDs of the mobile app.

Mobile developers can develop these events in their code, for example, to publish a ClickEvent whenever a customer clicks on their favorite sport (code shown below). In addition, you can define a BlueConic Listener to keep track of a customer's favorite category or sport.

You can add the ClickEvent to a function in your app, for example, by adding a click handler a customer interacts with in the UI or when they navigate to a different page. 

// Define click event for selector "#nextButton"
BlueConicClient.publishClickEvent("#favoriteSport",["soccer"]);

Once the developer adds the events within the app, BlueConic users at your site can define BlueConic Listeners to keep track of these events and store data to the profile. To create listeners for these events, they just have to know the selectors the developer used in their events (e.g. “#favoriteSport”).

BlueConic users can use the event feature in any of the following BlueConic Listeners:

mobile-listeners-set.png

Inside these listeners, BlueConic users can define the following rules with the event option:

  • Click/tab rule
  • Form Submit rule (only accessible in the Rule-Based Form Listener)
  • Advanced rule

When setting up the BlueConic Listener, under “Expert Settings,” you select the “Value from context of an event” option, as shown here:

behavior-listener.png

Subscribing to events

BlueConic allows you to subscribe to events received by the SDK from the platform when you use certain plugins or dialogues, in order to receive information from them. To subscribe to events, you can use the BlueConicEventManager with the following code:

import { EventName, CustomEvent(replace with specific event) } from '@blueconic/blueconic-react-native';

const eventEmitter = new NativeEventEmitter(BlueConicClient);

const customListener = useRef(null);

customListener.current = eventEmitter.addListener(
    "customEvent", // The name of the event to which you subscribe to
    (_customEvent: CustomEvent) = { // Callback that is invoked to handle information of the subscribed Event
        // Us the Event object to your specific event to retrieve event specific data
    }
);
BlueConicClient.subscribe(
    "customEvent", // The name of the event to which you subscribe to
    false, // Parameter specifying if the callback should be invoked only one time
    handlerIdentifier // Parameter used to identify the callback that can be used to unsubscribe
);

// Use to unsubscribe from events from the SDK using the defined identifier
customListener.current?.remove();
eventEmitter.removeAllListeners("customEvent");
BlueConicClient.unsubscribe(handlerIdentifier);

Depending on the configured plugin, the Event Handler function is invoked when the data from the server is received, specifically after PAGE VIEW events. Due to this, it is recommended that you set up your subscribed events before invoking any PAGE VIEW events.

BlueConic users can use the event subscribing feature for any of the following BlueConic plugins:

Properties Dialogue Event

To interact with the Properties-Based Dialogue plugin and receive the configured JSON data in your app, you need to subscribe to the Properties Dialogue Event. The received event in the handler will contain the data. To subscribe to the event, use the following implementation:

import { EventName, PropertiesDialogueEvent } from '@blueconic/blueconic-react-native';

const eventEmitter = new NativeEventEmitter(BlueConicClient);

const propertiesDialogueListener = useRef(null);

propertiesDialogueListener.current = eventEmitter.addListener(
    EventName.PropertiesDialogue, // The name of the event to which you subscribe to
    (_propertiesDialogueEvent: PropertiesDialogueEvent) = { // Callback that is invoked to handle information of the subscribed Event
        // Use _propertiesDialogueEvent to retrieve data (variantId, position & data)
    }
);
BlueConicClient.subscribe(
    EventName.PropertiesDialogue, // The name of the event to which you subscribe to
    false, // Parameter specifying if the callback should be invoked only one time
    handlerIdentifier // Parameter used to identify the callback that can be used to unsubscribe
);

// Use to unsubscribe from events from the SDK using the defined identifier
propertiesDialogueListener.current?.remove();
eventEmitter.removeAllListeners(EventName.PropertiesDialogue);
BlueConicClient.unsubscribe(handlerIdentifier);

The structure of the PropertiesDialogueEvent is as follows:

class PropertiesDialogueEvent {
    variantId;
    position;
    data;
};

The data parameter, which is the JSON configured in the plugin, is a stringified JSON that you will need to convert to a JSON object or your specific data structure in the app.

Additional functionality

To retrieve the segments the current user is currently part of, use the following methods:

const segments = await BlueConicClient.getSegments();

Testing the SDK integration

Enable debug mode

Add the following setting to the BlueConicConfiguration object when initializing the SDK:

...BlueConicConfiguration.Builder()
    ...
    .setDebug(true)
    ...
    .build()

Note

Setting Debug to true will provide more logging and enable the use of the BlueConic Simulator.

Warning

When you publish your apps, Debug should always be set false.

iOS

Adding a URL Scheme key for the BlueConic Simulator

Locate your app's Information Property List file under "Supporting Files."
Select <project>-Info.plist and add a new row by right-clicking the top row and selecting "Add row." Set the following key name:

URL types

This creates an array that contains more property rows. Open "URL types" by clicking the triangle icon in front of the name to display the rows. Right-click "Item 0" and select "Add row." You can also add a new item, and add the new row within that item. Set the following key name:

URL Schemes

This creates another array. Add a new row to this array's "Item 0" and enter your app's "Bundle Identifier", for example:

com.blueconic.testApp

Full example of the URL schemes:

URL types

After you have added the URL scheme value, select the AppDelegate class and add the following method to enable Simulator functionality:

Swift Objective C
// AppDelegate.swift file
func application(application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] ) -> Bool {    BlueConic.getInstance(nil).setURL(url)    
    return true
}

Android

Adding intent filters to the AndroidManifest.xml for connecting to the Simulator

Configure your appId at the android:scheme attribute in the code fragment below. For example, "com.test.testapp". For more information on how to configure a connection to the BlueConic Simulator see: Testing a native mobile app in BlueConic.

<activity android:name=".MainActivity" android:label="@string/app_name">
  <intent-filter>
    <action android:name="android.intent.action.MAIN"/>
    <category android:name="android.intent.category.LAUNCHER"/>
  </intent-filter>
  <!-- Filter added for connecting to the Simulator through mail .-->
  <intent-filter>
    <action android:name="android.intent.action.SEND"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="text/plain"/>
  </intent-filter>
  <!-- Filter added for connecting to the Simulator through a QR scan. -->
  <intent-filter>
    <action android:name="android.intent.action.VIEW"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <category android:name="android.intent.category.BROWSABLE"/>
    <data android:scheme="<Your appId>"/>
  </intent-filter>
</activity>

Additionally, you can pass Simulator information directly to the SDK when you initialize it in the BlueConicConfiguration object, if you know your Simulator username and mobile session ID, by using the following method:

...BlueConicConfiguration.Builder()
    ...
    .setSimulatorUsername(simulatorUsername)
    .setSimulatorSessionId(simulatorSessionId)
    ...
    .build()

Note

The use of the BlueConic Simulator is restricted to Debug mode only.

To test your mobile app, you will need access to a BlueConic environment. There are two options:

  • Are you working on behalf of a BlueConic Customer that has a BlueConic environment set up? Ask a representative of the BlueConic Customer to request a Sandbox environment in which you can test your mobile app.
  • Alternatively, request a free Pyxis environment yourself, and test your mobile app with that instance of BlueConic.

For more information on how to configure connecting to the BlueConic simulator see: Testing a native mobile app in BlueConic.


Migration guide

Migrating to version 4.x.x

Starting with version 4.x.x, the following changes need to be taken into account if you have an older version of the SDK:

  • The SDK no longer uses the app plist to retrieve the BlueConic hostname for iOS. The file can be safely removed.
  • The SDK no longer uses an XML configuration file to retrieve the BlueConic hostname for Android. The file can be safely removed.
  • The SDK now requires that you first initialize it, before doing any other API calls. When initializing, you now pass your BlueConic hostname in the initialization configuration object.
  • All functions with the suffix "Sync" have been renamed to "Async" to better describe the operation. Additionally, if the functions had both "Sync" and "WithCallback" suffixes, the "Sync" was removed. Now, the functions have the "Async" or "WithCallback" suffix depending on their functionality.
  • The SDK functions for PAGEVIEW, CLICK, VIEW, and CONVERSION events have been renamed and use the naming structure "create{EVENT}Event...".
  • The SDK functions for ADVANCED, CLICK, FORM SUBMIT, UPDATE CONTENT, and UPDATE VALUES have been renamed and use the naming structure "publish{EVENT}Event...".

Release Notes

To see a list of updates and bug fixes for the SDK, see the BlueConic SDK for React Native Release Notes

Was this article helpful?
0 out of 0 found this helpful