React Native SDK

Detailed technical documentation on the Lemnisk React Native SDK to send data from your React Native apps to your destinations via Lemnisk.

This document acts as a reference for the React Native SDK documentation. Please ensure that you have an agreed upon Event Tracking Plan from your Lemnisk Customer Success Point of Contact in conjunction with this document for the correct and complete implementation.

What is the Lemnisk React Native SDK?

Lemnisk React Native SDK can be used to track and send user events from your React Native application to various destinations of your choice. These destinations can be configured in the CDP Dashboard.

Installing the Lemnisk React Native SDK

The recommended way to install the React Native SDK is through npm. You may also use yarn to install the SDK.

  • Add the Lemnisk React Native dependency to your project by using the following command:

npm install --save lemnisk-react-native
  • Run the following command to update the Pods in your Project'sios directory:

If you are using React Native version below 0.60, then please run the following command to link the Lemnisk React Native SDK:

react-native link lemnisk-react-native

If you want to integrate Clevertap as a destination, please follow the steps documented here.

Steps for Android

Manifest File Changes

In the Package Explorer, open the AndroidManifest.xml of your Android project and make the following changes

Add the below meta tags, replacing the placeholders with associated values given below:

<meta-data
	android:name="Lemnisk.WRITE_KEY"
	android:value="{Writekey}" />
	
<meta-data
	android:name="Lemnisk.SERVER_URL"
	android:value="{serverUrl}" />
	
<!-- DEBUG_MODEis used to show Lemnisk debug/error/info logs. Set this to false when for Production environments -->
<meta-data
	android:name="Lemnisk.DEBUG_MODE"
	android:value="{true/false}" /> 
	
<!-- In production environment to enable push notifications keep the value android:value="true" -->
<meta-data
 	android:name="Lemnisk.ENABLE_PUSH"
 	android:value="{true/false}" />

The CampaignId and serverUrl will be provided by the Lemnisk Account Manager.

Configuring App Push Push Notifications

Lemnisk sends push notifications to Android devices using Firebase Cloud Messaging.

Add Firebase SDK

  • Lemnisk account manager will provide google-services.json. This google-services.json needs to be placed at root level in the app module.

  • Gradle changes

Project-level build.gradle (/build.gradle):

buildscript { 
    dependencies { 
        // Add this line classpath 
        'com.google.gms:google-services:4.3.3' 
    } 
}

App-level build.gradle (<project>/<app-module>/build.gradle):

dependencies { 
    // Add this line compile 
    'com.google.firebase:firebase-core:17.4.2' 
} ...
 
// Add to the bottom of the fileapply plugin: 
'com.google.gms.google-services'

Manifest Changes

In the Package Explorer open the AndroidManifest.xml of your Android project and make the following changes:

Add the following meta-tags

<meta-data 
    android:name="Lemnisk.NOTIFICATION_ICON" 
    android:resource="{NOTIFICATION_ICON}" />
<meta-data 
    android:name="Lemnisk.NOTIFICATION_ICON_SMALL" 
    android:resource="{NOTIFICATION_ICON_SMALL}" />
  • NOTIFICATION_ICON is displayed at the left of a notification

  • NOTIFICATION_ICON_SMALL is displayed in the notification bar. This should be white icon on a transparent background

Refer to Android Notifications and Style Icons for more details.

Add the following services for receiving the FCM token and messages.

<service
	android:name="co.lemnisk.app.android.push.LemFirebaseMessagingService">
        <intent-filter>
		<action android:name="com.google.firebase.MESSAGING_EVENT"/>
	</intent-filter>
</service>

<service
	android:name="co.lemnisk.app.android.push.LemFirebaseInstanceIdService">
	<intent-filter>
		<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
	</intent-filter>
</service>

Mandatory intent service for doing the heavy lifting

<service 
   android:name="co.lemnisk.app.android.push.LemIntentService"
   android:exported="false"
>
</service>

To support app-based deep link from Android 11 and onwards, following permission needs to be added to AndroidManifest.xml of the app.

AndroidManifest.xml
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>

OPT-IN for Push Notifications

If you are targeting Api level >= 33 then you must ask user permission for push notifications at runtime. For that you can call the below function at appropriate place in your app.

//You can change the title and message as you need.
LemniskSdk.registerForPushNotifications( "title", "message");

//if you don't provide the title and message default values will be given.
LemniskSdk.registerForPushNotifications();

Steps for iOS

Integration through CocoaPods

CocoaPods is a dependency manager for Objective C & Swift projects and makes integration easier.

  • If you don't have CocoaPods installed, you can do it by executing the following line in your terminal:

sudo gem install cocoapods
  • If you don't have a Podfile, create a plain text file named Podfile in the Xcode project directory with the following content, making sure to set the platform and version that matches your main app, Notification Content Extension and Notification Service Extension. Add the below code in the Podfile

If you are using SDK version <= 3.8.5 then add the extensions as mentioned below.

platform :ios, 'YOUR_TARGET_PLATFORM_VERSION'

target 'YOUR_TARGET_NAME' do  
    # Your App dependencies
end

# We will be adding following 2 extensions in the further steps given below
target 'NotificationContentExtension' do

  # Lemnisk Notification Content Extension
  pod 'Lemnisk-NotificationContent', '3.8.5'
end

target 'NotificationServiceExtension' do

  # Lemnisk Notification Service Extension
  pod 'Lemnisk-NotificationService', '3.8.5'
end

If you are using SDK version >= 3.8.6 then add the extensions as mentioned below.

platform :ios, 'YOUR_TARGET_PLATFORM_VERSION'

target 'YOUR_TARGET_NAME' do  
    # Your App dependencies
end

# We will be adding following 2 extensions in the further steps given below
target 'NotificationContentExtension' do

  # Lemnisk Notification Content Extension
  pod 'Lemnisk-iOS-SDK', '3.8.6'
end

target 'NotificationServiceExtension' do

  # Lemnisk Notification Service Extension
  pod 'Lemnisk-iOS-SDK', '3.8.6'
end

Initializing the iOS SDK

  • Import the Lemnisk SDK by using the following import statement in your AppDelegate or at the entry point of your App if it is iOS 15+

If the entry point is a .m file, use the following import statement.

#import <Lemnisk/Lemnisk.h>

If the entry point is a .mm file use the following instead

#import <Lemnisk/Lemnisk-Swift.h>

In the bridging header for the entry point file you need to add below import statements.

#import <UserNotifications/UserNotifications.h>
#import <UserNotificationsUI/UserNotificationsUI.h>
  • In your AppDelegate or in the entry point file, please add the following code snippet in didFinishLaunchingWithOptions to initialise the Lemnisk SDK.

  • Please enable Push Notifications and AppGroup capability from our Xcode Signing & Capabilities Tab and use the Same AppGroup for all the 3 targets (App, Notification Service Extension and Notification Content Extension). You can find the documentation here on how to enable AppGroup if you aren't familiar with this.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  {
    // Your code
    [[Lemnisk shared] setAppGroupIDWithGroupId:@"your app groupid"];  // This will be something like co.lemnisk.app.ios.bankingdemo
    [[Lemnisk shared] configureWithWriteKey:@"writeKey" serverUrl:@"xx-pl.lemnisk.co" launchOptions: launchOptions];
    // Your code
  }

Note: Lemnisk account manager will provide you with the values for writeKey and serverUrl.

If you want to show the Push Notifications permission authorization prompt from AppDelege itself, then you can use the following SDK API to show the same to the user. If you wish to show the otherization from your ReactJs using JavaScript then you can skip then and use the respective SDK method described in the later sections.

[[Lemnisk shared] registerForPushNotifications];

Please ignore any of the compilation errors at this point in time till the pod install command is run, which we will do in later steps

If you are using multiple push providers and using SDK version >= 3.8.6 you need to follow below steps.

In your AppDelegate you need to disable swizzling and then only call registerForPushNotifications

// Your code
Lemnisk.shared.setSwizzle(state: false)
Lemnisk.shared.setSwizzleForAll(state: false)
Lemnisk.shared.registerForPushNotifications()
// Your code

After you add above code you need to call our Lemnisk methods in your UIApplicationDelegate methods as mentioned below

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // Your code
    Lemnisk.shared.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
    // Your code
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    // Your code
    Lemnisk.shared.application(application, didFailToRegisterForRemoteNotificationsWithError: error)
    // Your code
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // Your code
    Lemnisk.shared.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
    // Your code
}

Rich Push Setup

From iOS 10+, we can show rich media Push Notifications with images, video, audio and a carousel. So please configure the below 2 extensions in your project if you don't have them already and configure Lemnisk SDK in them.

Notification Service Extension

We use Notification Service Extension to track the delivery of Push Notifications as well as downloading the Rich Media Push Notification attachments (image/video/audio etc)

  • Add a Notification Service Extension target to your project (File -> New -> Target -> Notification Service Extension)

  • Define the name for the Notification Service Extension in the next step

Now please enable the AppGroup capability from our Xcode Signing & Capabilities Tab and use the same AppGroup for all the 3 targets (App, Notification Service Extension and Notification Content Extension). You can find the documentation here on how to enable AppGroup if you aren't familiar with this.

Now modify the NotificationService.swift to look like the following code.

If you are using SDK version below 3.8.5 then use the below code.

import UserNotifications
import LemniskRichNotification

class NotificationService: LemniskNotificationService {

    public override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        super.setAppGroupID(groupId: "your app groupid") // This will be something like co.lemnisk.app.ios.bankingdemo that you have created above
        super.didReceive(request, withContentHandler: contentHandler)
    }

    public override func serviceExtensionTimeWillExpire() {
        super.serviceExtensionTimeWillExpire()
    }
}

If you are using version 3.8.5 and above modify the NotificationService.swift to look like the following code.

import UserNotifications
//if SDK version <= 3.8.5
import LemniskRichNotification
// else if SDK version >= 3.8.6
import Lemnisk

class NotificationService: UNNotificationServiceExtension {
    public override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        LemniskNotificationService.shared.setAppGroupID(groupId: "your app groupid") // This will be something like co.lemnisk.app.ios.bankingdemo that you have created above
        LemniskNotificationService.shared.didReceive(request, withContentHandler: contentHandler)
    }
    
    public override func serviceExtensionTimeWillExpire() {
        LemniskNotificationService.shared.serviceExtensionTimeWillExpire()
    }
}

If you have multiple push providers and using sdk version >= 3.8.6 you can implement NotificationService as mentioned below.

import UserNotifications
import Lemnisk

class NotificationService: UNNotificationServiceExtension {

    var bestAttemptContent: UNMutableNotificationContent?
    var isLemPush: Bool?
    
    public override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

        self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        self.isLemPush = false
        
        var userInfo: [String: Any]? = bestAttemptContent?.userInfo as? [String: Any]

        if Lemnisk.shared.isLemniskPush(userInfo: userInfo) {
            self.isLemPush = true
            LemniskNotificationService.shared.setAppGroupID(groupId: "your app groupid")
            LemniskNotificationService.shared.didReceive(request, withContentHandler: contentHandler)
        }
        else{
            //other push provider code
        }
    }
    
    public override func serviceExtensionTimeWillExpire() {
        if(self.isLemPush == true){
            super.serviceExtensionTimeWillExpire()
        }
        else{
            //other push provider code
        }
    }
}

Notification Content Extension

This extension can be used if you want to show a carousel slider in a Push Notification.

  • Add a Notification Content Extension target to your project (File -> New -> Target -> Notification Content Extension)

  • Define the name for the Notification Content Extension in the next step.

  • Make sure the deployment target for notification content is set to iOS 10

  • Now please enable the AppGroup capability from our Xcode Signing & Capabilities Tab and use the same AppGroup for all the 3 targets (App, Notification Service Extension and Notification Content Extension). You can find the documentation here on how to enable AppGroup if you aren't familiar with this.

  • Now modify the NotificationViewController.swift to look like the following code.

import UIKit
import UserNotifications
import UserNotificationsUI
// if sdk version <= 3.8.5
import LemniskNotificationContent
// else if sdk version >= 3.8.6
import Lemnisk

class NotificationViewController:  LemniskNotificationViewController {

    override func viewDidLoad() {
        super.viewDidLoad();
    }

    override func didReceive(_ notification: UNNotification) {
        super.setAppGroupID(groupId: "your app groupid") // This will be something like co.lemnisk.app.ios.bankingdemo that you have created above
        super.didReceive(notification)
    }
}

Now install all the Lemnisk dependencies with the following command

pod install

Note: If you are running this for the first time then you may need to update the pod repositories by running:

pod install --repo-update
  • This would install the Lemnisk framework along with the required dependencies for your app extension targets.

Changes in Frameworks, Libraries, and Embedded content for Notification Service Extension( only if sdk version <= 3.8.5)

For some reason, there is an issue with Pods being installed and Xcode reading it from the embedded pod's. And so we need to embed the LemniskRichNotification manually in the extension target's Frameworks, Libraries, and Embedded content and select Do Not Embed. You can refer to the same below.

Now select Do Not Embed

Changes in Frameworks, Libraries, and Embedded content for Notification Content Extension( only if sdk version <= 3.8.5)

For some reason, there is an issue with Pods being installed and Xcode reading it from the embedded pod's. And so we need to embed the LemnsikNotificationContent manually in the extension targets Frameworks, Libraries, and Embedded content and select Do Not Embed. You can refer to the same below.

Now select Do Not Embed

Changes in Frameworks, Libraries, and Embedded content for the App Target( only if sdk version <= 3.8.5)

For some reason, there is an issue with Pods being installed and Xcode reading it from the embedded pod's. So you may end up seeing this error when you are trying to validate your build.

To resolve this, we need to embed the LemniskRichNotification and LemnsikNotificationContent manually in the Application target's Frameworks, Libraries, and Embedded content and select Embed & Sign. You can refer to the same below.

Configuring App Groups

Please follow the following procedure if you are using the Xcode Auto Sign, otherwise please scroll below to add the App Groups manually via the Apple Developer Console.

With Xcode Auto Sign

  • Go to App Groups capability from the Xcode’s Singing & Capabilities for all the targets (App, NotificationServiceExtension and NotificationContentExtension) as shown in the following screenshot.

  • Now search for App group and select App Groups

  • Now create the required App Groups Id by inputting a value similar to your Bundle Id (need not be same as BundleId) which will have group. as the prefix

  • Now finally select group id that we have just created

  • Similarly, select the already created same AppGroup for the other two targets - Notification Service Extension and Notification Content Extension.

Now close and reopen your project's xc-workspace file and at this point in time, all the build errors should be resolved.

From Apple Developer Console

  • Goto Identifiers tab in the Apple Developer Console and click on App Groups as shown in the below screenshot.

  • Now tap + to create a new App Group

  • Select App Groups on the next screen as shown below

  • Now fill the Description and the Identifier (App Group name) and click Continue

  • On the next screen, click Register

  • Now go to Identifiers tab, click on your App Bundle identifier

  • Now check on App Groups and click configure

  • On the next step, select the group we have created in the previous step and click continue and then Save

  • Now go to Profile tab and select your profile, if it shows invalid then click Edit and Save. Then download the file and use it in the Xcode.

  • Finally in the Xcode, go to Singing & Capabilities as shown in the following screenshot

  • Now search for App group and select App Groups

  • Now select the App group that we have created earlier in the Apple Developer Console

  • Now repeat steps 6-12 for App extension targets as well (Now go to Identifiers step above)

Info.plist Configuration

App

  • Please add the Privacy - Tracking Usage Description key in your main app Info.plist as this will be used as a description while showing the Tracking description if you would want to enable the IDFA tracking.

  • To enable/disable the IDFA tracking you can do so by adding the properties LemniskUseIDFA and LemniskShowIDFAPrompt as Boolean to your main app's Info.plist file.

Please find the description of the above LemniskUseIDFA and LemniskShowIDFAPrompt below

  • LemniskUseIDFA - Will grant IDFA usage to Lemnisk

  • LemniskShowIDFAPrompt - To ask the user for Tracking permission or not

Notification Content Extension

  1. Please update the Notification Content Extension Info.plist's UNNotificationExtensionCategory to Array and add the required categories from the following entries.

    i. carousel

  2. Add the following properties under NSExtensionAttributes

    i. Add property UNNotificationExtensionDefaultContentHidden as String and set its value to YES

    ii. Add property UNNotificationExtensionUserInteractionEnabled as Boolean and set its value to true

3. Initializing the Lemnisk React Native SDK

Once the SDK is added, you need to initialize the React Native SDK.

  • Import the SDK wherever you'd like to use it in your react codebase

import LemniskSdk from 'lemnisk-react-native';

4. SDK API Methods

Push Notification Authorization Prompt

If you want to show the Push Notification Authorization Prompt from your React Native code on any screen from your JS code, then you can call the following SDK API. Given you haven't already called this from your AppDelegate.

LemniskSdk.registerForPushNotifications();

Screen

The screen call lets you record whenever a user sees a screen, in your mobile app, along with any properties about the screen.

Usage:

LemniskSdk.screen('screen_name', {properties}, {otherIds})

Example:

LemniskSdk.screen("home", {
  "variation": "carousel",
  "buttons": 2
 }, {
	"trackerId": "6791c47a-0178-47bc-8711-86a2c67b2255"
})

Identify

The identify call lets you tie a user to their actions and record traits about them. It includes a unique User ID and any optional traits you know about the user, like their email, mobile, any other id etc.

Usage:

LemniskSdk.identify('userId', {traits}, {otherIds})

Example:

LemniskSdk.identify('crmid1234', {
	"firstName": "John",
	"lastName": "Miller",
	"gender": "Male",
}, {
	"email": "john@gmail.com"
})

Track

The track call lets you record any actions your users perform, along with any properties that describe the action.

Usage:

LemniskSdk.track('eventName', {properties}, {otherIds})

Example:

LemniskSdk.track('Product View', {
	"productName": "iPhone 13",
	"productCategory": "Mobiles",
	"price": "799",
	"currency": "USD",
}, {
	"email": "john@gmail.com"
})

Configuring APNS Certificates

Lemnisk would need the cert.pem and key.pem files generated for your application to be able to send the App Push Notifications.

Following is the procedure to generate the cert.pem and key.pem files.

Generating the CSR and p12

Open Keychain Access on your Mac (it is in Applications/Utilities) and choose the menu option Request a Certificate from a Certificate Authority

You should now see the following window:

  1. Enter your email address here.

  2. Enter your application name here, for example, I have entered "LemniskDemo". You can type anything you want here, but choose something descriptive. This allows us to easily find the private key later.

  3. Check Saved to disk and click Continue.

If you go to the Keys section of Keychain Access, you will see that a new private key has appeared in your keychain.

Right-click on the new private key and choose Export.

Save the private key as LemniskDemoKey.p12 and enter a passphrase. (Do choose a passphrase that you can recall! Or you won’t be able to use the private key later.)

So log in to the Apple developer console & follow the below steps:

Generating the aps cert

Assuming you have already created the Identifier for your app bundle id, now navigate to the Certificates section in the developer console. Click on the + next to Certificates

Choose the Apple Push Notification service SSL (Sandbox & Production) option and click on Continue

Now select the App Id from the already registered (of your app) list in the Identifier section and then click on Continue

Now click on Choose File and select the CSR file that we have generated above and click on Continue

Now we have successfully generated the aps.cer file, click on Download to download the cer file. Let’s say the downloaded file name is aps.cer

Generating the PEM file

So now we have three files:

  1. The CSR

  2. The private key as a p12 file (LemniskDemoKey.p12)

  3. The SSL certificate (aps.cer)

You have to convert the certificate and private key into a format that is more usable. Because our server will need the cert.pem and key.pem file to deliver the push notification, now we will generate them by using the following procedure.

We are going to use the command-line OpenSSL tools for this. Open a Terminal and execute the following steps.

Convert the .cer file into a .pem file:

$ openssl x509 -in aps.cer -inform der -out LemniskDemoCert.pem

Convert the private key’s .p12 file into a .pem file:

$ openssl pkcs12 -nocerts -out LemniskDemoKey.pem -in LemniskDemoKey.p12

 Enter Import Password: 

 MAC verified OK
 
 Enter PEM pass phrase: 

 Verifying - Enter PEM pass phrase: 

You first need to enter the passphrase for the .p12 file so that openssl can read it. Then you need to enter a new passphrase that will be used to encrypt the PEM file.

Note: if you don’t enter a PEM passphrase, openssl will not give an error message but the generated .pem file will not have the private key in it.

Now let’s try to test whether the certificate works, by using our SSL certificate and private key:

$ openssl s_client -connect gateway.push.apple.com:2196 -cert LemniskDemoCert.pem -key LemniskDemoKey.pem

    Enter pass phrase for LemniskDemoCert.pem:

Now please share the following with your account manager for us to be able to send push notifications

  1. cert.pem and key.pem (Generated above)

  2. passphrase (if any given in the above steps)

  3. bundle identifier of the app

5. FAQs

Q1. What is the minimum Android and iOS versions supported by the Lemnisk React Native SDK?

Ans: iOS 13 and Android 5.0 or higher is supported.

Q2. I get the error LemniskSdk is not defined. What do I do?

This error appears when you try to use the LemniskSdk method before initialising the SDK in the application. Make sure to import the SDK at the top of your file before using it.

import LemniskSdk from 'lemnisk-react-native';

Q3. Is it required to link the SDK using react native link ?

If you running an older version of React Native, v.60 or lower, yes, it is mandatory to link the SDK with the react native link command.

Q4. How to verify if the Lemnisk React Native SDK is installed correctly?

Import the SDK and run the application on your mobile device. If it runs without any errors, it is safe to assume that the SDK is installed and loaded correctly.

Q5. I built an app using Expo. Can I install the Lemnisk React Native SDK with it?

No, because as of now, Expo doesn't support adding native modules in their application. However, you can eject your expo app and use our native Android and iOS libraries.

Q6. I am facing some performance issues with the SDK. What could be the issue?

React Native runs slow in DEBUG mode. Try running the code in Production. Follow this article to learn more. If it is still slow in Production mode, make sure the Lemnisk.DEBUG_MODE is also set to false in AndroidManifest.xml file.

Common Troubleshooting Steps

In case you encounter any issues with the SDK, follow the steps below to fix the errors and run the SDK correctly.

  1. Make sure that the SDK is installed and loaded properly. If npm install or yarn add is giving any problem while installation, please upgrade npm or yarn to the latest version.

  2. Please check whether you are running on VPN or proxy that prevents SDK from functioning properly.

  3. Make sure your system date and time is correct.

  4. If nothing works, please contact us below.

Contact Us

To know more about the Lemnisk React Native SDK you can contact us.

Last updated