*react-native-sentiance
is still in an early development stage and not ready for production use just yet. Please try it out, give feedback, and help fix bugs.
https://github.com/sentiance/react-native-sentiance-example
$ npm install react-native-sentiance --save
with Cocoapods
- Add
RNSentiance
Pod to your Podfilepod 'RNSentiance', :path => '../node_modules/react-native-sentiance/ios/RNSentiance.podspec'
- Add
SENTSDK
Pod to your Podfilepod 'SENTSDK', :podspec => '../node_modules/react-native-sentiance/ios/SENTSDK.podspec'
- Run
pod install
in yourios
folder
without Cocoapods
- Download the latest version of the Sentiance iOS SDK from our developer documentation.
- In XCode, in the project navigator, right click
Libraries
âžśAdd Files to [your project's name]
- Go to
node_modules
âžśreact-native-sentiance-library
and addRNSentianceLibrary.xcodeproj
- In XCode, in the project navigator, select
RNSentianceLibrary.xcodeproj
. Add the folder whereSENTSDK.framework
is located toSearch Paths
âžśFramework Search Paths
- In XCode, in the project navigator, select your project. Add
libRNSentianceLibrary.a
to your project'sBuild Phases
âžśLink Binary With Libraries
- Run your project (
Cmd+R
)<
Configuring capabilities
- Go to the Capabilities tab of your target settings
- Turn on Background Modes and enable Location updates
- Turn off Data protection
In your AppDelegate
add the following:
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
@import SENTSDK;
#import <RNSentiance.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:@"RNSentiance"
initialProperties:nil];
// Read SENTIANCE_APP_ID and SENTIANCE_APP_SECRET from any safe source
NSString * SENTIANCE_APP_ID = @"";
NSString * SENTIANCE_APP_SECRET = @"";
[[bridge moduleForName:@"RNSentiance"] initSDK:SENTIANCE_APP_ID secret:SENTIANCE_APP_SECRET baseURL:nil shouldStart:YES resolver:nil rejecter:nil];
.....
return YES;
}
- Open up youd application class
android/app/src/main/java/[...]/{your-app-class}.java
- Add
import com.reactlibrary.RNSentiancePackage;
to the imports at the top of the file - Add
new RNSentiancePackage()
to the list returned by thegetPackages()
method
- Append the following lines to
android/settings.gradle
:include ':react-native-sentiance' project(':react-native-sentiance').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-sentiance/android')
- Insert the following lines inside the dependencies block in
android/app/build.gradle
:compile project(':react-native-sentiance')
- Add following entry to
android/build.gradle
allprojects { repositories { ... maven { url "http://repository.sentiance.com" } } }
- Configure foreground notification, Add the following lines to application's
AndroidManifest.xml
file inside<application>
tag:<meta-data android:name="com.sentiance.react.bridge.notification_title" android:resource="@string/app_name"/> <meta-data android:name="com.sentiance.react.bridge.notification_text" android:value="Touch to open."/> <meta-data android:name="com.sentiance.react.bridge.notification_icon" android:resource="@mipmap/ic_launcher"/> <meta-data android:name="com.sentiance.react.bridge.notification_channel_name" android:value="Sentiance"/> <meta-data android:name="ccom.sentiance.react.bridge.notification_channel_id" android:value="sentiance"/>
Inside Application#onCreate()
method, initialize and start sentiance SDK
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
RNSentianceHelper rnSentianceHelper = RNSentianceHelper.getInstance(getApplicationContext());
rnSentianceHelper.initializeSentianceSDK(
SENTIANCE_APP_ID,SENTIANCE_SECRET, // app id and secret
true, //auto start
null, // init callback
null // start callback
);
...
}
NOTE: Ideally, initializing the SDK is done from AppDelegate's didFinishLaunchingWithOptions
or Application's onCreate
method as this will guarantee that the SDK is running as often as possible. If your application uses a login flow, you will want to start the SDK only if the user is logged in, at that point you could start the SDK through JavaScript. Once the user is logged in, the SDK should always start before the end of onCreate or didFinishLaunchingWithOptions
. Please refer to https://docs.sentiance.com/ for documentation on the SDK integration.
import RNSentiance from 'react-native-sentiance';
Initialize and start sentiance SDK.
try {
const startResponse = await RNSentiance.init(
APP_ID,APP_SECRET, // app id and secret
null, // override base url
true, // auto start
);
} catch (err) {
// SDK did not start.
}
If SDK is not started automatically i.e autoStart = false
during init, it can be started manually.
try {
const startResponse = await RNSentiance.start();
const { startStatus } = startResponse;
if (startStatus === 'STARTED') {
// SDK started properly.
} else if (startStatus === 'PENDING') {
// Something prevented the SDK to start properly. Once fixed, the SDK will start automatically.
}
} catch (err) {
// SDK did not start.
}
Stopping is only allowed after successful initialization. While it's possible to "pause" the detections modules of the Sentiance SDK's, it's not recommended.
try {
const stopResponse = await RNSentiance.stop();
// SDK stopped properly.
} catch(err) {
// An error prevented the SDK from stopping correctly
}
Checking if SDK is initialized
const initState = await RNSentiance.getinitstate();
const isInitialized = initState == "INITIALIZED";
The status of the Sentiance SDK
const sdkStatus = await RNSentiance.getSdkStatus();
The SDK can signal SDK status updates to JavaScript without being invoked directly. You can subscribe to these status updates by creating a new NativeEventEmitter instance around your module, and adding a listener for SDKStatusUpdate
.
import { NativeEventEmitter } from 'react-native'
const sentianceEmitter = new NativeEventEmitter(RNSentiance);
const subscription = sentianceEmitter.addListener(
'SDKStatusUpdate',
res => {
// Returns SDK status
}
);
// Don't forget to unsubscribe, typically in componentWillUnmount
subscription.remove();
const version = await RNSentiance.getVersion();
If the SDK is initialized, you can get the user id as follows. This user id will allow you to interact with the API's from Sentiance. You need a token and user to authorize requests and query the right data.
const userId = await RNSentiance.getUserId();
If the SDK is initialized, you can get a user access token as follows. This token will allow you to interact with the API's from Sentiance. You need a token and user to authorize requests and query the right data. If the token has expired, or will expire soon, the SDK will get a new bearer token before passing it to the callback. Generally, this operation will complete instantly by returning a cached bearer token, but if a new token has to be obtained from the Sentiance API, there is a possibility it will fail.
const { tokenId } = await RNSentiance.getUserAccessToken();
Custom metadata allows you to store text-based key-value user properties into the Sentiance platform. Examples are custom user id's, application related properties you need after the processing, ...
const label = 'correlation_id'
const value = '3a5276ec-b2b2-4636-b893-eb9a9f014938'
await RNSentiance.addUserMetadataField(label, value);
You can remove previously added metadata fields by passing the metadata label to the removeUserMetadataField function.
const label = 'correlation_id'
await RNSentiance.removeUserMetadataField(label);
You can add multiple custom metadata fields by passing an object to the addUserMetadataFields function.
const metadata = { corrolation_id: '3a5276ec-b2b2-4636-b893-eb9a9f014938' }
await RNSentiance.addUserMetadataFields(metadata);
Whenever you call startTrip on the SDK, you override moving state detection and the SDK will track the trip until you call stopTrip or until the timeout (2 hours) is reached. startTrip
accepts a metadata object and a transport mode hint (number
) as parameters.
Transport mode hint:
SENTTransportModeUnknown = 1,
SENTTransportModeCar = 2,
SENTTransportModeBicycle = 3,
SENTTransportModeOnFoot = 4,
SENTTransportModeTrain = 5,
SENTTransportModeTram = 6,
SENTTransportModeBus = 7,
SENTTransportModePlane = 8,
SENTTransportModeBoat = 9,
SENTTransportModeMetro = 10,
SENTTransportModeRunning = 11
Example:
const metadata = { corrolation_id: '3a5276ec-b2b2-4636-b893-eb9a9f014938' }
const transportModeHint = 1
try {
await RNSentiance.startTrip(metadata, transportModeHint);
// Trip is started
} catch (err) {
// Unable to start trip
}
try {
const trip = await RNSentiance.stopTrip();
// Stopped trip
} catch (err) {
// Unable to stop trip
}
The SDK can also signal trip timeouts to JavaScript. You can subscribe to these trip timeouts by creating a new NativeEventEmitter instance around your module, and adding a listener for TripTimeout
.
import { NativeEventEmitter } from 'react-native'
const sentianceEmitter = new NativeEventEmitter(RNSentianceLibrary)
const subscription = sentianceEmitter.addListener(
'TripTimeout',
() => {
// Trip timeout received
}
)
Checking trip status
const isTripOngoing = await RNSentiance.isTripOngoing();
If you want to override the default behavior, you can initiate a force submission of detections. Ideally, you use this method only after explaining to the user that your app will consume more bandwidth in case the device is not connected to Wi-Fi.
try {
await RNSentiance.submitDetections();
} catch (err) {
// Something went wrong with submitting data, for more information, see the error variable
}
The actual usages and limits in bytes can be obtained using the getWiFiQuotaUsage, getWiFiQuotaLimit and similar methods on the Sentiance SDK interface.
const limit = await RNSentiance.getWiFiQuotaLimit();
All quota functions:
getWiFiQuotaLimit
getWiFiQuotaUsage
getMobileQuotaLimit
getMobileQuotaUsage
getDiskQuotaLimit
getDiskQuotaUsage
Get user current activity
const userActivity = await RNSentiance.getUserActivity();
The SDK can signal user activity updates to JavaScript without being invoked directly. You can subscribe to these user activity updates by creating a new NativeEventEmitter instance around your module, and adding a listener for SDKUserActivityUpdate
.
import { NativeEventEmitter } from 'react-native'
const sentianceEmitter = new NativeEventEmitter(RNSentiance);
const subscription = sentianceEmitter.addListener(
'SDKUserActivityUpdate',
userActivity => {
// Returns SDK status
}
);
// Don't forget to unsubscribe, typically in componentWillUnmount
subscription.remove();
Handling user activity
const { type, tripInfo, stationaryInfo } = userActivity;
if (type === 'USER_ACTIVITY_TYPE_STATIONARY') {
const { location } = stationaryInfo;
if (location) {
const { latitude, longitude } = location;
}
//..
} else if (type === 'USER_ACTIVITY_TYPE_TRIP') {
//..
} else if (type === 'USER_ACTIVITY_TYPE_UNKNOWN') {
//..
}
Updates the title and text of SDK notification. After calling this method, any notification shown by the SDK will be updated.
Note that this change is valid only during the process's lifetime. After the app process restarts, the SDK will display the default notification.
/**
* {string} title
* {string} message
*/
await RNSentiance.updateSdkNotification("RN SDK Sample", "SDK is running");
During initialization if user linking is enabled SDK will send SDKUserLink
event along with instalId
. This install id should be linked to third party id and after successful linking call RNSentiance.userLinkCallback(true)
to notify the SDK.
Please refer to https://docs.sentiance.com/guide/user-linking for documentation on the user linking.
import { NativeEventEmitter } from 'react-native'
const sentianceEmitter = new NativeEventEmitter(RNSentiance);
sentianceEmitter = rnSentianceEmitter.addListener(
"SDKUserLink",
id => {
const { installId } = id;
//send this installid to you server for linking
linkUser(installId);
//once linking is done notify sdk
RNSentiance.userLinkCallback(true)
}
);