Skip to content

React Native App Integration


Prerequisites

Note

If the RUM Headless service has been activated, the prerequisites have been configured automatically and you can proceed directly to app integration.

App Integration

Note

The current React Native version only supports Android and iOS platforms.

  1. Navigate to User Analysis > Create > React Native;
  2. Input the app name;
  3. Input the app ID;
  4. Select the app integration method:

    • Public DataWay: Directly receives RUM data without requiring DataKit collector installation.
    • Local Environment Deployment: Receives RUM data after meeting the prerequisites.

Installation

Source Code Address: https://github.com/GuanceCloud/datakit-react-native

Demo Address: https://github.com/GuanceCloud/datakit-react-native/example

Run the following command in your project directory via terminal:

npm install @cloudcare/react-native-mobile

This will add the following line to your package.json file:

"dependencies": {    
   "@cloudcare/react-native-mobile: [lastest_version],
   ···
}

Additional Configuration for Android:

  • Configure Gradle Plugin ft-plugin to collect App startup events and network request data, as well as Android Native related events (page transitions, click events, Native network requests, WebView data).
  • Note that you need to configure the Guance Android Maven repository address simultaneously in Gradle, both Plugin and AAR are required. Refer to the configuration details in example build.gradle.

Now, in your code, you can use:

import {
  FTMobileReactNative,
  FTReactNativeLog,
  FTReactNativeTrace,
  FTReactNativeRUM,
  FTMobileConfig,
  FTLogConfig,
  FTTraceConfig,
  FTRUMConfig,
  ErrorMonitorType,
  DeviceMetricsMonitorType,
  DetectFrequency,
  TraceType,
  FTLogStatus,
  EnvType,
} from '@cloudcare/react-native-mobile';

SDK Initialization

Basic Configuration

 //Local environment deployment, Datakit deployment
let config: FTMobileConfig = {
    datakitUrl: datakitUrl,
  };

 //Use public DataWay
 let config: FTMobileConfig = {
    datawayUrl: datawayUrl,
    clientToken: clientToken
  };
await FTMobileReactNative.sdkConfig(config);
Field Type Required Description
datakitUrl string Yes Local environment deployment (Datakit) reporting URL address, example: http://10.0.0.1:9529, default port 9529, the device installing the SDK must be able to access this address. Note: choose either datakitUrl or datawayUrl
datawayUrl string Yes Public Dataway reporting URL address, obtained from the [User Analysis] application, example: https://open.dataway.url, the device installing the SDK must be able to access this address. Note: choose either datakitUrl or datawayUrl
clientToken string Yes Authentication token, needs to be used together with datawayUrl
debug boolean No Set whether to allow log printing, default false
env string No Environment configuration, default prod, any character, suggest using a single word, e.g., test etc.
envType enum EnvType No Environment configuration, default EnvType.prod. Note: only one of env or envType needs to be configured
service string No Set the name of the business or service, affects the service field data in Logs and RUM. Default: df_rum_ios, df_rum_android
autoSync boolean No Whether to automatically synchronize data to the server after collection, default true. When set to false, use FTMobileReactNative.flushSyncData() to manage data synchronization yourself
syncPageSize number No Set the number of entries per sync request. Range [5,). Note: the larger the number of entries, the more computational resources will be used for data synchronization
syncSleepTime number No Set the intermittent time for synchronization. Range [0,5000], default not set
enableDataIntegerCompatible boolean No Suggested to enable when coexisting with web data. This configuration is used to handle web data type storage compatibility issues. Automatically enabled in versions 0.3.12 and later
globalContext object No Add custom tags. Rules for adding tags can be found here
compressIntakeRequests boolean No Compress uploaded sync data using deflate compression, default disabled
enableLimitWithDbSize boolean No Enable limiting data size using db, default 100MB, unit Byte, the larger the database, the greater the disk pressure, default not enabled.
Note: After enabling, the Log configuration logCacheLimitCount and RUM configuration rumCacheLimitCount will become invalid. Supported by SDK versions 0.3.10 and above
dbCacheLimit number No DB cache limit size. Range [30MB,), default 100MB, unit byte, supported by SDK versions 0.3.10 and above
dbDiscardStrategy string No Set the data discard rule for the database.
Discard strategy: FTDBCacheDiscard.discard discards new data (default), FTDBCacheDiscard.discardOldest discards old data. Supported by SDK versions 0.3.10 and above

RUM Configuration

let rumConfig: FTRUMConfig = {
    androidAppId: Config.ANDROID_APP_ID,
    iOSAppId:Config.IOS_APP_ID,
    enableAutoTrackUserAction: true,
    enableAutoTrackError: true,
    enableNativeUserAction: true,
    enableNativeUserView: false,
    enableNativeUserResource: true,
    errorMonitorType:ErrorMonitorType.all,
    deviceMonitorType:DeviceMetricsMonitorType.all,
    detectFrequency:DetectFrequency.rare
  };

await FTReactNativeRUM.setConfig(rumConfig);
Field Type Required Description
androidAppId string Yes app_id, applied in the User Analysis console
iOSAppId string Yes app_id, applied in the User Analysis console
sampleRate number No Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1. Scope applies to all View, Action, LongTask, Error data under the same session_id
enableAutoTrackUserAction boolean No Whether to automatically collect React Native component click events, enables setting actionName via accessibilityLabel, refer to here for more customization options
enableAutoTrackError boolean No Whether to automatically collect React Native Errors, default false
enableNativeUserAction boolean No Whether to track Native Action, such as native Button click events and app startup events, default false
enableNativeUserView boolean No Whether to perform automatic tracking of Native Views, pure React Native applications are recommended to turn this off, default false
enableNativeUserResource boolean No Whether to start automatic tracking of Native Resources, since React-Native's network requests on iOS and Android use system APIs, enabling enableNativeUserResource allows all resource data to be collected. Default false
errorMonitorType enum ErrorMonitorType No Set auxiliary monitoring information, add additional monitoring data to RUM Error data, ErrorMonitorType.battery for battery level, ErrorMonitorType.memory for memory usage, ErrorMonitorType.cpu for CPU utilization, default not enabled
deviceMonitorType enum DeviceMetricsMonitorType No In the View lifecycle, add monitoring data, DeviceMetricsMonitorType.battery (only Android) monitors the highest output current of the current page, DeviceMetricsMonitorType.memory monitors the memory usage of the current application, DeviceMetricsMonitorType.cpu monitors CPU jumps, DeviceMetricsMonitorType.fps monitors screen frame rate, default not enabled
detectFrequency enum DetectFrequency No Sampling cycle for view performance monitoring, default DetectFrequency.normal
enableResourceHostIP boolean No Whether to collect the IP address of the requested target domain. Scope: only affects the default collection when enableNativeUserResource is true. iOS: supported on >= iOS 13. Android: Okhttp caches IP addresses for the same domain, so under the same OkhttpClient, only one instance is generated if the connection to the server IP does not change.
globalContext object No Add custom tags for distinguishing user monitoring data sources. If tracking functionality is needed, then parameter key should be track_id, value can be any number. Refer to here for rules and notes
enableTrackNativeCrash boolean No Whether to monitor Android Java Crash and OC/C/C++ crashes, default false
enableTrackNativeAppANR boolean No Whether to monitor Native ANR, default false
enableTrackNativeFreeze boolean No Whether to collect Native Freeze, default false
nativeFreezeDurationMs number No Set the threshold for collecting Native Freeze stalls, range [100,), unit milliseconds. iOS default 250ms, Android default 1000ms
rumDiscardStrategy string No Discard strategy: FTRUMCacheDiscard.discard discards new data (default), FTRUMCacheDiscard.discardOldest discards old data
rumCacheLimitCount number No Maximum local cache limit for RUM entries [10_000,), default 100_000

Log Configuration

let logConfig: FTLogConfig = {
      enableCustomLog: true,
      enableLinkRumData: true,
    };
await FTReactNativeLog.logConfig(logConfig);
Field Type Required Description
sampleRate number No Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1.
enableLinkRumData boolean No Whether to link with RUM
enableCustomLog boolean No Whether to enable custom logs
logLevelFilters Array No Log level filtering
globalContext NSDictionary No Add custom log tags, refer to here for rules
logCacheLimitCount number No Maximum local cache limit for log entries [1000,), larger logs mean higher disk cache pressure, default 5000
discardStrategy enum FTLogCacheDiscard No Set the log discard rule when reaching the limit. Default FTLogCacheDiscard.discard, discard discards appended data, discardOldest discards old data

Trace Configuration

 let traceConfig: FTTractConfig = {
      enableNativeAutoTrace: true, 
    };
await FTReactNativeTrace.setConfig(traceConfig);
Field Type Required Description
sampleRate number No Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1.
traceType enum TraceType No Trace type, default TraceType.ddTrace
enableLinkRUMData boolean No Whether to link with RUM data, default false
enableNativeAutoTrace boolean No Whether to enable automatic tracing of native network requests iOS NSURLSession , Android OKhttp (since React Native's network requests on iOS and Android use system APIs, enabling enableNativeAutoTrace allows all React Native data to be tracked.)

Note:

  • Please complete the SDK initialization before registering the App in your top-level index.js file to ensure the SDK is fully ready before calling any other SDK methods.
  • Complete the basic configuration before proceeding to RUM, Log, and Trace configurations.
import App from './App';

async function sdkInit() {
  await FTMobileReactNative.sdkConfig(config);
  await FTReactNativeRUM.setConfig(rumConfig);
  ....
}
initSDK();
AppRegistry.registerComponent('main', () => App);

RUM User Data Tracking

View

When initializing the SDK RUM Configuration, you can enable enableNativeUserView to automatically collect Native Views. Since React Native Views provide extensive libraries for creating screen navigation, manual collection is supported by default. You can manually start and stop views using the following methods.

Custom View

Usage Method
/**
 * View loading duration.
 * @param viewName view name
 * @param loadTime view loading duration
 * @returns a Promise.
 */
onCreateView(viewName:string,loadTime:number): Promise<void>;
/**
 * View start.
 * @param viewName interface name
 * @param property event context (optional)
 * @returns a Promise.
 */
startView(viewName: string, property?: object): Promise<void>;
/**
 * View end.
 * @param property event context (optional)
 * @returns a Promise.
 */
stopView(property?:object): Promise<void>;
Example Usage
import {FTReactNativeRUM} from '@cloudcare/react-native-mobile';

FTReactNativeRUM.onCreateView('viewName', duration);

FTReactNativeRUM.startView(
  'viewName',
  { 'custom.foo': 'something' },
);

FTReactNativeRUM.stopView(
 { 'custom.foo': 'something' },
);

Automatic Collection of React Native Views

If you are using react-native-navigation, react-navigation, or Expo Router navigation components in React Native, you can reference the methods below for automatic collection of React Native Views:

react-native-navigation

Add the FTRumReactNavigationTracking.tsx file from the example to your project;

Call the FTRumReactNativeNavigationTracking.startTracking() method to start collection.

import { FTRumReactNativeNavigationTracking } from './FTRumReactNativeNavigationTracking';

function startReactNativeNavigation() {
  FTRumReactNativeNavigationTracking.startTracking();
  registerScreens();//Navigation registerComponent
  Navigation.events().registerAppLaunchedListener( async () => {
    await Navigation.setRoot({
      root: {
        stack: {
          children: [
            { component: { name: 'Home' } },
          ],
        },
      },
    });
  });
}
react-navigation

Add the FTRumReactNavigationTracking.tsx file from the example to your project;

  • Method One:

If you use createNativeStackNavigator(); to create a native navigation stack, it is recommended to add screenListeners to start collection. This way, the page loading duration can be recorded. Specific usage is as follows:

  import {FTRumReactNavigationTracking} from './FTRumReactNavigationTracking';
  import { createNativeStackNavigator } from '@react-navigation/native-stack';
  const Stack = createNativeStackNavigator();

  <Stack.Navigator  screenListeners={FTRumReactNavigationTracking.StackListener} initialRouteName='Home'>
          <Stack.Screen name='Home' component={Home}  options={{ headerShown: false }} />
          ......
          <Stack.Screen name="Mine" component={Mine} options={{ title: 'Mine' }}/>
  </Stack.Navigator>
  • Method Two:

If createNativeStackNavigator(); is not used, you need to add the automatic collection method in the NavigationContainer component, as shown below:

Note: This method cannot collect page loading duration

  import {FTRumReactNavigationTracking} from './FTRumReactNavigationTracking';
  import type { NavigationContainerRef } from '@react-navigation/native';

  const navigationRef: React.RefObject<NavigationContainerRef<ReactNavigation.RootParamList>> = React.createRef();
  <NavigationContainer ref={navigationRef} onReady={() => {
        FTRumReactNavigationTracking.startTrackingViews(navigationRef.current);
      }}>
        <Stack.Navigator initialRouteName='Home'>
          <Stack.Screen name='Home' component={Home}  options={{ headerShown: false }} />
          .....
          <Stack.Screen name="Mine" component={Mine} options={{ title: 'Mine' }}/>
        </Stack.Navigator>
   </NavigationContainer>

For specific usage examples, refer to example.

Expo Router

If you are using Expo Router, add the following method in the app/_layout.js file for data collection.

import { useEffect } from 'react';
import { useSegments, Slot } from 'expo-router';
import {
  FTReactNativeRUM,
} from '@cloudcare/react-native-mobile';

export default function Layout() {
    const segments = useSegments();
    const viewKey = segments.join('/');

    useEffect(() => {
       FTReactNativeRUM.startView(viewKey);
    }, [viewKey, pathname]);

    // Export all the children routes in the most basic way.
    return <Slot />;
}

Action

In the SDK initialization RUM Configuration, configure enableAutoTrackUserAction and enableNativeUserAction to enable automatic collection, or manually add using the following methods.

Usage Method

/**
 * Start RUM Action. RUM will bind possible Resource, Error, LongTask events triggered by this Action.
 * Avoid multiple additions within 0.1 s. Only one Action can be associated with the same View at the same time, 
 * and new Actions will be discarded if the previous Action has not ended. Adding Actions using `addAction` does not affect each other.
 * @param actionName action name
 * @param actionType action type
 * @param property event context (optional)
 * @returns a Promise.
 */
startAction(actionName:string,actionType:string,property?:object): Promise<void>;
 /**
  * Add Action event. This type of data cannot be associated with Error, Resource, LongTask data, and there is no discard logic.
  * @param actionName action name
  * @param actionType action type
  * @param property event context (optional)
  * @returns a Promise.
  */
addAction(actionName:string,actionType:string,property?:object): Promise<void>;

Code Example

import {FTReactNativeRUM} from '@cloudcare/react-native-mobile';

FTReactNativeRUM.startAction('actionName','actionType',{'custom.foo': 'something'});

FTReactNativeRUM.addAction('actionName','actionType',{'custom.foo': 'something'});

More Custom Collection Operations

After enabling enableAutoTrackUserAction, the SDK will automatically collect clicks of components with the onPress attribute. If you wish to execute some custom operations based on automatic tracking, the SDK supports the following operations:

  • Customize the actionName for a component's click event

Set it via the accessibilityLabel attribute

  <Button title="Custom Action Name"
          accessibilityLabel="custom_action_name"
          onPress={()=>{
                console.log("btn click")
          }}
   />
  • Do not collect a component's click event

You can set the custom parameter ft-enable-track to false

  <Button title="Action Click" 
          ft-enable-track="false"
          onPress={()=>{
                console.log('btn click');
          }}
  />
  • Add extra attributes to a component's click event

You can set the custom parameter ft-extra-property, requiring a JSON string value

  <Button title="Action 添加额外属性"
          ft-extra-property='{"e_name": "John Doe", "e_age": 30, "e_city": "New York"}'
          onPress={()=>{
                 console.log("btn click")
          }}
  />

Error

In the SDK initialization RUM Configuration, configure enableAutoTrackError to enable automatic collection, or manually add using the following methods.

Usage Method

/**
 * Capture exceptions and collect logs.
 * @param stack stack log
 * @param message error message
 * @param property event context (optional)
 * @returns a Promise.
 */
addError(stack: string, message: string,property?:object): Promise<void>;
/**
 * Capture exceptions and collect logs.
 * @param type error type
 * @param stack stack log
 * @param message error message
 * @param property event context (optional)
 * @returns a Promise.
 */
addErrorWithType(type:string,stack: string, message: string,property?:object): Promise<void>;

Usage Example

import {FTReactNativeRUM} from '@cloudcare/react-native-mobile';

FTReactNativeRUM.addError("error stack","error message",{'custom.foo': 'something'});

FTReactNativeRUM.addErrorWithType("custom_error", "error stack", "error message",{'custom.foo': 'something'});

Resource

In the SDK initialization RUM Configuration, configure enableNativeUserResource to enable automatic collection, or manually add using the following methods.

Usage Method

/**
 * Start resource request.
 * @param key unique id
 * @param property event context (optional)
 * @returns a Promise.
 */
startResource(key: string,property?:object): Promise<void>;
/**
 * End resource request.  
 * @param key unique id
 * @param property event context (optional)
 * @returns a Promise.
 */
stopResource(key: string,property?:object): Promise<void>;
/**
 * Send resource data metrics.
 * @param key unique id
 * @param resource resource data
 * @param metrics  resource performance data
 * @returns a Promise.
 */
addResource(key:string, resource:FTRUMResource,metrics?:FTRUMResourceMetrics):Promise<void>;

Usage Example

import {FTReactNativeRUM} from '@cloudcare/react-native-mobile';

async getHttp(url:string){
            const key = Utils.getUUID();
            FTReactNativeRUM.startResource(key);
            const fetchOptions = {
                  method: 'GET',
                  headers:{
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                  } ,
            };
            var res : Response;
            try{
                  res = await fetch(url, fetchOptions);
            }finally{
                  var resource:FTRUMResource = {
                        url:url,
                        httpMethod:fetchOptions.method,
                        requestHeader:fetchOptions.headers,
                  };
                  if (res) {
                        resource.responseHeader = res.headers;
                        resource.resourceStatus = res.status;
                        resource.responseBody = await res.text();
                  }
                  FTReactNativeRUM.stopResource(key);
                  FTReactNativeRUM.addResource(key,resource);
            }
      }

Logger Log Printing

Current log content is limited to 30 KB, exceeding characters will be truncated.

Usage Method

/**
 * Output log.
 * @param content log content
 * @param status  log status
 * @param property log context (optional)
 */
logging(content:String,logStatus:FTLogStatus|String,property?:object): Promise<void>;

Usage Example

import { FTReactNativeLog, FTLogStatus } from '@cloudcare/react-native-mobile';
// logStatus:FTLogStatus
FTReactNativeLog.logging("info log content",FTLogStatus.info);
// logStatus:string
FTReactNativeLog.logging("info log content","info");

Log Levels

Method Name Meaning
FTLogStatus.info Informational
FTLogStatus.warning Warning
FTLogStatus.error Error
FTLogStatus.critical Critical
FTLogStatus.ok Recovery

Tracer Network Trace Tracking

During SDK initialization Trace Configuration, automatic network trace tracking can be enabled, and also supports user-defined collection. Usage methods and examples are as follows:

Usage Method

/**
 * Get trace http request header data.
 * @param url request address
 * @returns trace added request header parameters  
 * @deprecated use getTraceHeaderFields() replace.
 */
getTraceHeader(key:String, url: String): Promise<object>;
/**
 * Get trace http request header data.
 * @param url request address
 * @returns trace added request header parameters  
 */
getTraceHeaderFields(url: String,key?:String): Promise<object>;

Usage Example

import {FTReactNativeTrace} from '@cloudcare/react-native-mobile';

async getHttp(url:string){
    const key = Utils.getUUID();
    var traceHeader = await FTReactNativeTrace.getTraceHeaderFields(url);
    const fetchOptions = {
      method: 'GET',
      headers:Object.assign({
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },traceHeader) ,
    };
    try{
      fetch(url, fetchOptions);
    }
  }

User Information Binding and Unbinding

Usage Method

/**
 * Bind user.
 * @param userId user ID.
 * @param userName user name.
 * @param userEmail user email
 * @param extra  user extra information
 * @returns a Promise.
 */
bindRUMUserData(userId: string,userName?:string,userEmail?:string,extra?:object): Promise<void>;
/**
 * Unbind user.
 * @returns a Promise.
 */
unbindRUMUserData(): Promise<void>;

Usage Example

import {FTMobileReactNative} from '@cloudcare/react-native-mobile';

/**
 * Bind user.
 * @param userId user ID.
 * @param userName user name.
 * @param userEmail user email
 * @param extra  user extra information
 * @returns a Promise.
*/
FTMobileReactNative.bindRUMUserData('react-native-user','uesr_name')
/**
 * Unbind user.
 * @returns a Promise.
*/
FTMobileReactNative.unbindRUMUserData()

Closing the SDK

Use FTMobileReactNative to close the SDK.

Usage Method

/**
 * Close running objects within the SDK
 */
shutDown():Promise<void>

Usage Example

FTMobileReactNative.shutDown();

Clearing SDK Cache Data

Use FTMobileReactNative to clear uncached data that hasn't been reported yet.

Usage Method

/**
 * Clear all data that has not yet been uploaded to the server.
 */
clearAllData():Promise<void>

Usage Example

/**
 * Clear all data that has not yet been uploaded to the server.
*/
FTMobileReactNative.clearAllData();

Actively Sync Data

When FTMobileConfig.autoSync is set to true, no additional actions are required; the SDK will automatically sync data.

When FTMobileConfig.autoSync is set to false, you need to actively trigger the data sync method for synchronization.

Usage Method

/**
 * Actively sync data, when `FTMobileConfig.autoSync=false`, you need to actively trigger this method for data synchronization.
 * @returns a Promise.
 */
flushSyncData():Promise<void>;

Usage Example

FTMobileReactNative.flushSyncData();

Adding Custom Tags

Usage Method

/**
 * Add custom global parameters. Applies to RUM and Log data
 * @param context custom global parameters.
 * @returns a Promise.
 */
appendGlobalContext(context:object):Promise<void>;
/**
 * Add custom RUM global parameters. Applies to RUM data
 * @param context custom RUM global parameters.
 * @returns a Promise.
 */
appendRUMGlobalContext(context:object):Promise<void>;
/**
 * Add custom RUM and Log global parameters. Applies to Log data
 * @param context custom Log global parameters.
 * @returns a Promise.
 */
appendLogGlobalContext(context:object):Promise<void>;

Usage Example

FTMobileReactNative.appendGlobalContext({'global_key':'global_value'});

FTMobileReactNative.appendRUMGlobalContext({'rum_key':'rum_value'});

FTMobileReactNative.appendLogGlobalContext({'log_key':'log_value'});

Symbol File Upload

Automatic Packaging of Symbol Files

Add Script for Automatic Symbol File Packaging

Script tool: cloudcare-react-native-mobile-cli

cloudcare-react-native-mobile-cli is a script tool that helps configure the automatic acquisition of React Native and Native sourcemaps during release builds and packages them into zip files.

Add it locally to the package.json development dependencies.

For example, placing cloudcare-react-native-mobile-cli.tgz in the React Native project directory:

 "devDependencies": {
    "@cloudcare/react-native-mobile-cli":"file:./cloudcare-react-native-mobile-cli-v1.0.0.tgz",
  }

Execute yarn install after adding.

Note: Android environments require adding Gradle Plugin ft-plugin, version requirement: >=1.3.4

Add Plugin usage and parameter settings in the main module app's build.gradle file.

apply plugin: 'ft-plugin'
FTExt {
    //showLog = true
    autoUploadMap = true
    autoUploadNativeDebugSymbol = true
    generateSourceMapOnly = true
}

Execute Configuration Commands

Run the terminal command yarn ft-cli setup in the React Native project directory to automatically acquire React Native and Native sourcemaps during release builds and package them into zip files. Success is indicated by the following logs.

  example git:(test-cli)  yarn ft-cli setup
yarn run v1.22.22
$ /Users/xxx/example/node_modules/.bin/ft-cli setup
Starting command: Setup to automatically get react-native and native sourcemap in release build and package them as zip files.
Running task: Add a Gradle Script to automatically zip js sourcemap and Android symbols
Running task: Enable react-native sourcemap generation on iOS
Running task: Setup a new build phase in XCode to automatically zip dSYMs files and js sourcemap


Finished running command Setup to automatically get react-native and native sourcemap in release build and package them as zip files.

 Successfully executed: Add a Gradle Script to automatically zip js sourcemap and Android symbols.
 Successfully executed: Enable react-native sourcemap generation on iOS.
 Successfully executed: Setup a new build phase in XCode to automatically zip dSYMs files and js sourcemap.
  Done in 1.00s.

Release build zipped file location:

iOS: iOS folder (./ios/sourcemap.zip)

Android: RN project directory (./sourcemap.zip)

Manual Packaging of Symbol Files

React Native Zip Package Instructions

Upload

File Upload and Deletion

WebView Data Monitoring

To monitor WebView data, integrate the Web Monitoring SDK in the accessed pages.

Custom Tag Usage Example

Compilation Configuration Method

  1. Use react-native-config to configure multi-environments, setting corresponding custom tag values in different environments.
let rumConfig: FTRUMConfig = {
      iOSAppId: iOSAppId,
      androidAppId: androidAppId,
      monitorType: MonitorType.all,
      enableTrackUserAction:true,
      enableTrackUserResource:true,
      enableTrackError:true,
      enableNativeUserAction: false,
      enableNativeUserResource: false,
      enableNativeUserView: false,
      globalContext:{"track_id":Config.TRACK_ID}, //.env.dubug、.env.release 等配置的环境文件中设置
    };

 await FTReactNativeRUM.setConfig(rumConfig); 

Runtime Read/Write File Method

  1. Through persistent data methods like AsyncStorage, obtain stored custom tags during SDK initialization.
 let rumConfig: FTRUMConfig = {
      iOSAppId: iOSAppId,
      androidAppId: androidAppId,
      monitorType: MonitorType.all,
      enableTrackUserAction:true,
      enableTrackUserResource:true,
      enableTrackError:true,
      enableNativeUserAction: false,
      enableNativeUserResource: false,
      enableNativeUserView: false,
    };
 await new Promise(function(resolve) {
       AsyncStorage.getItem("track_id",(error,result)=>{
        if (result === null){
          console.log('获取失败' + error);
        }else {
          console.log('获取成功' + result);
          if( result != undefined){
            rumConfig.globalContext = {"track_id":result};
          }
        }
        resolve(FTReactNativeRUM.setConfig(rumConfig));
      })
     });
  1. Add or modify custom tags in arbitrary locations.
AsyncStorage.setItem("track_id",valueString,(error)=>{
    if (error){
        console.log('存储失败' + error);
    }else {
        console.log('存储成功');
    }
})
  1. Restart the app for changes to take effect.

SDK Runtime Addition

After SDK initialization, use FTReactNativeRUM.appendGlobalContext(globalContext), FTReactNativeRUM.appendRUMGlobalContext(globalContext), FTReactNativeRUM.appendLogGlobalContext(globalContext) to dynamically add tags. Settings take immediate effect, and subsequent RUM or Log data uploads will automatically include tag data. This method is suitable for scenarios where data needs to be delayed, such as tags requiring network requests.

//SDK initialization pseudocode, obtaining
FTMobileReactNative.sdkConfig(config);

function getInfoFromNet(info:Info){
    let  globalContext = {"delay_key":info.value}
    FTMobileReactNative.appendGlobalContext(globalContext);
}

Native and React Native Hybrid Development

If your project is natively developed and partially uses React Native for certain pages or business processes, the SDK installation and initialization configuration methods are as follows:

  • Installation: Installation remains unchanged

  • Initialization: Refer to iOS SDK Initialization Configuration and Android SDK Initialization Configuration to initialize within the native project.

  • React Native Configuration:

    RN SDK 0.3.11 support

    No additional initialization is required on the React Native side. If you need to automatically collect React Native Error and React Native Action, follow these steps:

    import {FTRumActionTracking,FTRumErrorTracking} from '@cloudcare/react-native-mobile';
    //Enable automatic collection of react-native control clicks
    FTRumActionTracking.startTracking();
    //Enable automatic collection of react-native Errors
    FTRumErrorTracking.startTracking();
    
  • Native Project Configuration:

    RN SDK 0.3.11 support

    When enabling RUM Resource automatic collection, filter out React Native symbolization calls and Expo log calls that occur only in the development environment. Methods are as follows:

    iOS

    ```objective-c

    ```objective-c

    import

    import

FTRumConfig *rumConfig = [[FTRumConfig alloc]initWithAppid:rumAppId]; rumConfig.enableTraceUserResource = YES;

if DEBUG

rumConfig.resourceUrlHandler = ^BOOL(NSURL * _Nonnull url) { return [FTReactNativeUtils filterBlackResource:url]; };

endif

=== "Swift"

```swift
import FTMobileReactNativeSDK
import FTMobileSDK

let rumConfig = FTRumConfig(appId: rumAppId)
rumConfig.enableTraceUserResource = true
#if DEBUG
rumConfig.resourceUrlHandler = { (url: URL) -> Bool in
   return FTReactNativeUtils.filterBlackResource(url)
}
#endif

Android

import com.cloudcare.ft.mobile.sdk.tracker.reactnative.utils.ReactNativeUtils;
import com.ft.sdk.FTRUMConfig;

FTRUMConfig rumConfig = new FTRUMConfig().setRumAppId(rumAppId);
rumConfig.setEnableTraceUserResource(true);
if (BuildConfig.DEBUG) {
    rumConfig.setResourceUrlHandler(new FTInTakeUrlHandler() {
      @Override
      public boolean isInTakeUrl(String url) {
        return ReactNativeUtils.isReactNativeDevUrl(url);
      }
    });
}
import com.cloudcare.ft.mobile.sdk.tracker.reactnative.utils.ReactNativeUtils
import com.ft.sdk.FTRUMConfig

val rumConfig = FTRUMConfig().setRumAppId(rumAppId)
rumConfig.isEnableTraceUserResource = true
if (BuildConfig.DEBUG) {
  rumConfig.setResourceUrlHandler { url ->
    return@setResourceUrlHandler ReactNativeUtils.isReactNativeDevUrl(url)
}

For specific usage examples, refer to example.

Android

iOS

Common Issues

Feedback

Is this page helpful? ×