Skip to content

React Native

Initialization

In order to create ease for partners, we have divided the SDK into multiple modules. Each module represents a specific app niche that partners can use based on their app category. For this step, we will only focus on the core sdk

In order to use the SDK, Core is mandatory to include as it contains the elements regarding the basic app navigation and workflow including nudges. Moreover, all the modules require the core to be integrated in order to successfully log the events.

The easiest way to integrate Causal Foundry React Native (Android) SDK in your project is using an NPM package. Add dependencies of react-native SDK in the dependencies section of your package.json of your project and Android Lifecycle Components in the app/build.gradle file.

"@causalfoundry/react-native-cf-core" : "<version_number>"

for version_number please head to npm package.

After including the above, Open terminal/shell and go to your project directory, and run:

npm install

if you are using expo to build your react-native application, Please follow the instructions on the expo guidelines to integrate native modules. As Causal Foundry react native SDK uses android native modules to utilise OS level APIs to ensure optimal results.

As SDK requires app events to auto manage the logging of user sessions you also need to include android lifecycle dependency in your android app/build.gradle file.

If you are using expo for your React Native application then you need to move to bare workflow by expo to integrate the SDK as the Causal Foundry SDK uses android native modules to utilise OS level APIs to ensure optimal results. You DO NOT need to eject from expo just for the Causal Foundry SDK. If you are using React Native CLI, you can skip to here the following steps

Steps for Expo

To make use of Causal Foundry SDK and continue with the same developer experience of Expo Go, you can migrate to using development builds. Development builds are like your own personal version of Expo Go — they include the native runtime that powers your app, and you control what is included in that native runtime by adding or removing packages in your package.json. Development builds allow you to continue to build your app in JavaScript while taking advantage of the full ecosystem of native packages available for Expo and React Native projects.

Open terminal window, go to your apps directory, and run the prebuild command.

npx expo prebuild

Using the run commands will initially prebuild your project to generate all of the native code within your project directory. If you manually modify the android or ios directory, you won't be able to safely re-run npx expo prebuild, this is known as the bare workflow.

Your app can still run in Expo Go, however, any custom native code won't be accessible if it's not already present in the Expo Go app. After creating the prebuild, you need to update your scripts for start in package.json and remove --dev-client if it is already added, update as:

"scripts": {
"start": "expo start",
...
},

In some cases you need to reconfigure your Expo modules after creating the prebuild which creates android and iOS folders in your project. To reconfigure expo modules run the following command in your project directory:

npx install-expo-modules@latest

Once you have the setup ready, you can create development builds for your android and iOS applications as:

# Run the app on android
npx expo run:android

# Run the app on iOS
npx expo run:ios

or you can create local development server as well:

npm run start
# Will run the script mentioned above in the package.json

This will generate the QR code for you that you can scan in Expo Go or by camera app in iOS to download builds.

SDK Initialization for Android

After following the above, you can open /android folder in android studio and continue with SDK initialization as below.

Lifecycle components are required, if you already have them in your project you may skip them. To add the dependency, open your android folder in Android Studio and open the app-level build.gradle file and in your dependencies add the following:

dependencies {

    //LifecycleComponents
    implementation 'androidx.lifecycle:lifecycle-process:2.3.1'

}

Create an Application class in your project and include LifecycleEventObserver Components. Initialize Android SDK with your SDK Token from onCreate callback of your Application class as shown below.

public class MainApplication extends Application implements ReactApplication, LifecycleEventObserver {

    @Override
  public void onCreate() {
    super.onCreate();

      // to observe Application lifecycle events
      ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

  }

    /*
        In onStateChanged() function include the following function to auto-track events related to app and activity lifecycle.
    */
    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        CfLogCore.CfSDKInit(this, event);
    }

Causal Foundry Android SDK requires an SDK key in order to log events. To do so, you need to create an SDK key from the Causal Foundry Platform and pass it to the SDK using the app's Manifest file as meta-data like below:

<meta-data android:name="ai.causalfoundry.android.sdk.APPLICATION_KEY"
           android:value="<SDK_KEY_HERE>"/>

Causal Foundry Android SDK also allows you to update track events after the user’s usage session is over. SDK sends the events whenever the app goes into the background. This helps in not overloading the user’s phone while in use. SDK handles the events even in offline mode and ensures that they get uploaded to the portal whenever the user connects to the internet. SDK also auto logs the App Open, close, and background events so, you don't have to implement those.

Don't forget to include android:name=".MyApplication" in your manifest's application tag.

SDK Initialization for iOS

For ios initialization, you need to have a mac and Xcode installed and min deployment target as ios 13.0.

From your React Native project, head to /ios folder and run

pod install

this will install all the necessary pods for your including the Causal Foundry SDk pods too.

once the Pods are successfully installed, head to your info.plist file and add the following keys for the Permitted background task scheduler identifiers

ai.causalfoundry.ingestAppEvents
        ai.causalfoundry.fetchNudges

        OR

<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>ai.causalfoundry.ingestAppEvents</string>
<string>ai.causalfoundry.fetchNudges</string>
</array>

ios_info_plist.png

After adding the values in info.plist, head to the app Target project > Signing & Capabilities > Background Modes and select the following 2:

  • Background fetch
  • Background processing

ios_background_task.png

Once the background tasks are selected, create a new swift class named CFSDK, when creating a new swift class you will be prompted to also create a Bridging-Header file, allow that as well and inside you bridging header class, add the following header:

#import <React/RCTBridgeModule.h>

In yourCFSDK swift class, add the following init method:

import Foundation
import CausalFoundrySDKCore

@objc(CFSDK)
class CFSDK: NSObject {

    @objc
    func initCFSDK(){
        CausualFoundry.shared.configure()

        CFLogBuilder()
            .setUsageForReactNative()
            .allowAnonymousUsers()
            .setSdkKey(sdkKey: "<SDK_KEY_FROM_CF_PLATFORM>")
            .disableAutoPageTrack()
            .build()      
        print("CF SDK init")
    }
}

Once the above is added, head to your AppDelegate.mm for initialization of the above function.

CFSDK *cfSDK = [[CFSDK alloc] init];
[cfSDK initCFSDK];

Now try build your project, CF SDK should be initialized and ready to use.

Note that since we are using BGTaskScheduler for ios SDK, the events will not be sent exactly after the app the closed but will be sent at a later time on the availability of the resources by the OS.


Additional steps for Expo

Ejecting to bare workflow comes with a couple of additional steps dus to multiple architectural differences.

Node Modules in Dependencies | Native Event Emitter Error

After ejecting from Expo, head to your node_modules > @causalfoundry > [SDK directory] and delete the node_modules inside that directory. By default the node_modules of the project should be used to overcome any dependency mismatch issues.

Failed resolution of: Lorg/koin/dsl/ModuleKt; | Koin Version Mismatch

As both Expo and CF Android ASK uses Koin, you might encounter koin version mismatch error on android devices (depending on the version of the Expo you are using), to deal with such please downgrade the version of koin in your expo gradle file implementation "io.insert-koin:koin*** to 3.1.2, you might also need to add koin core, depending on the other dependencies you use with expo, as bare workflow might not include the core in some instances but for most cases it is not required as all.





Causal Foundry SDK automatically starts tracking user data (e.g., Upload/download speed, OS version, device IDs) and engagement with the basic setup above. This data can be stored on the device and uploaded in batches to reduce network and power usage, and to increase the likelihood of successful uploads while you can also upload the events as soon as they happen. The upload is done when the user device session ends. SDK also starts tracking user sessions with this basic setup.

Each event can further be understood in the context of its attributes which includes details like time, upload/download speed, device details, locale, online/offline usage, screen time, interactions, and so on. This enables you to gain in-depth insights into user interactions across your app. You can also leverage this data to segment users, personalize messages and configure campaign targeting.



Next Steps -> Adding Core Events