• Before using, please read the Data Model
  • Sensors Analytics react-native-sensors-analyticsmodule encapsulates common APIs of Sensors Analytics Android & iOS SDKs. By using this module, you can complete tracking and statistical reporting in React Native developed apps.

  • For SDK updates, please refer to the Release Notes

1. Integrate the Sensors Analytics SDK RN module

For applications developed with React Native, you can integrate the Sensors Analytics SDK RN module using npm or yarn methods.

1.1. Install the Sensors Analytics SDK RN module

npm install sensorsdata-analytics-react-native
CODE
yarn add sensorsdata-analytics-react-native
CODE

Link the Sensors Analytics SDK RN module

Note: React Native versions 0.60 and above use autolinking and do not require the react-native link command.

react-native link sensorsdata-analytics-react-native
CODE

1.2. Execute the command

Execute the node command in the project directory

node node_modules/sensorsdata-analytics-react-native/SensorsDataRNHook.js -run
CODE

Note: If you need to restore the original code, you can execute the reset command

node node_modules/sensorsdata-analytics-react-native/SensorsDataRNHook.js -reset
CODE

2. iOS End

2.1. Integrate the Sensors Analytics iOS SDK

2.1.1. Use CocoaPods for integration

Execute the following command in the project directory:

 cd ios && pod install && cd .. 
CODE

Only support React Native 0.60.0 and above versions

2.1.2. Integrate using source code

  1. Get the source code of the iOS SDK from [GitHub](https://github.com/sensorsdata/sa-sdk-ios) and put the extracted source code into the ios folder of the React Native project;
  2. Open the iOS project of the React Native project, and add SensorsAnalyticsSDK.xcodeproj to the Libraries folder in the iOS project;
  3. Add SensorsAnalyticsSDK.framework to "General" → "Frameworks, Libraries, Embedded Content";
  4. Add the following dependency libraries to "Build Phase" → "Link Binary With Libraries": libicucore, libsqlite3, and libz;
  5. Add code for different modules:
    1. The Core folder contains the core files of the SDK and is added by default;
    2. The Location folder collects location information. If you don't need to collect location information, you can remove this folder from the project;
    3. For integration with H5, the SDK supports the new version of integration scheme using WKWebView by default. If you want to use the old version of integration scheme, you can import the WebView folder. If you are using UIWebView, you can import the WebView folder;

2.2. Initialize the Sensors Analytics SDK;

2.2.1. Get the data receiving URL for the project;

  • Each project has a separate data receiving URL;
  • Please use an administrator account to obtain the data receiving URL for the corresponding project;

![Data Access](https://scroll-translations.addons.k15t.com/xliff/ri:filename="数据接入.png")

2.2.2. Initialize the SDK;

Add the initialization code in the -application:didFinishLaunchingWithOptions: method of AppDelegate:

//引入神策分析 SDK #import <SensorsAnalyticsSDK/SensorsAnalyticsSDK.h> // 初始化配置 SAConfigOptions *options = [[SAConfigOptions alloc] initWithServerURL:<#数据接收地址#> launchOptions:launchOptions]; // 开启全埋点,可根据需求进行组合 options.autoTrackEventType = SensorsAnalyticsEventTypeAppStart | SensorsAnalyticsEventTypeAppEnd | SensorsAnalyticsEventTypeAppClick | SensorsAnalyticsEventTypeAppViewScreen; #ifdef DEBUG // SDK 开启 Log options.enableLog = YES; #endif /** * 其他配置 */ // 初始化 SDK [SensorsAnalyticsSDK startWithConfigOptions:options];
CODE

2.3. Configure the Scheme;

2.3.1. Get the project Scheme;

  • The project Scheme needs to be obtained using an administrator account;
  • The App project can configure the Scheme of multiple projects at the same time;

Same as where you get the data receiving URL, as shown in the figure below:

2.3.2. Add Scheme in the App

Select Target->Info->URL Types in the iOS project of the React Native project, click the plus sign (+), and configure the Scheme obtained in the previous step in URL Types:

2.3.3. Process the Incoming URL

In AppDelegate's -application:openURL:options: method, call -handleSchemeUrl: to process the Sensors Analytics Scheme.

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{ if ([[SensorsAnalyticsSDK sharedInstance] canHandleURL:url]) { return [[SensorsAnalyticsSDK sharedInstance] handleSchemeUrl:url]; } return NO; }
CODE

3. Android

3.1. Integrate and Initialize the Sensors Analytics Android SDK

Please refer to the integration documentation (Android).

3.2. Configure ProGuard

If you have obfuscation in your project after integrating the Sensors Analytics SDK RN module, you need to add the following configuration to the obfuscation file.

-dontwarn com.sensorsdata.analytics.** -keep class com.sensorsdata.analytics.** { *; }
CODE

3.3. Integrate Using Android Studio Packaging

If you want to integrate React Native components into an Android application, you need to add RNSensorsAnalyticsPackage and implement the corresponding callbacks in the Activity that loads ReactRootView.

Code example:

import com.sensorsdata.analytics.RNSensorsAnalyticsPackage; ... public class RNPageActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler { private ReactRootView mReactRootView; public static ReactInstanceManager mReactInstanceManager; private final static String TAG = "RNPageActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mReactRootView = new ReactRootView(this); mReactInstanceManager = ReactInstanceManager.builder() .setApplication(getApplication()) .setCurrentActivity(this) .setBundleAssetName("index.android.bundle") .setJSMainModulePath("index") .addPackage(new MainReactPackage()) .addPackage(new RNSensorsAnalyticsPackage()) // 添加 RNSensorsAnalyticsPackage .setUseDeveloperSupport(BuildConfig.DEBUG) .setInitialLifecycleState(LifecycleState.RESUMED) .build(); // 这个"App1"名字一定要和我们在index.js中注册的名字保持一致AppRegistry.registerComponent() mReactRootView.startReactApplication(mReactInstanceManager, "App1", null); setContentView(mReactRootView); } @Override public void invokeDefaultOnBackPressed() { super.onBackPressed(); } @Override protected void onResume() { super.onResume(); if (mReactInstanceManager != null) { mReactInstanceManager.onHostResume(this, this); Log.d(TAG, "onResume"); } } @Override protected void onPause() { super.onPause(); if (mReactInstanceManager != null) { mReactInstanceManager.onHostPause(this); Log.d(TAG, "onPause"); } } @Override public void onBackPressed() { if (mReactInstanceManager != null) { mReactInstanceManager.onBackPressed(); Log.d(TAG, "onBackPressed"); } else { super.onBackPressed(); } } @Override protected void onDestroy() { super.onDestroy(); if (mReactInstanceManager != null) { mReactInstanceManager.onHostDestroy(this); Log.d(TAG, "onDestroy"); } if (mReactRootView != null) { mReactRootView.unmountReactApplication(); } } public boolean onKeyUp(int keyCode, KeyEvent event) { if (BuildConfig.DEBUG) { if (keyCode == KeyEvent.KEYCODE_MENU) {//Ctrl + M 打开RN开发者菜单 mReactInstanceManager.showDevOptionsDialog(); return true; } } return super.onKeyUp(keyCode, event); } }
CODE

It is necessary to implement onResume(), onPause(), onDestroy() callback methods and call mReactInstanceManager.onHostResume(this, this), mReactInstanceManager.onHostPause(this), mReactInstanceManager.onHostDestroy(this) methods in these callback methods. Otherwise, the click event may not be triggered for full event tracking.

4. Initialize on React Native

4.1. Import the Sensors Analytics module

In the specific js file, import the Sensors Analytics React Native module. The import module is as follows:

import sensors from 'sensorsdata-analytics-react-native'
CODE

Initialization

sensors.init({ server_url:'数据接收地址', auto_track:SAAutoTrackType.START|SAAutoTrackType.END|SAAutoTrackType.CLICK|SAAutoTrackType.VIEW_SCREEN })
CODE

4.1.1.1. Initialization attribute description

Attribute NameAttribute TypeAttribute DescriptionNotes
server_urlstringData Receiving URL
show_logbooleanWhether to display logsDefault false
global_propertiesobjectGlobal properties

Android SDK 6.4.3 and above

iOS SDK 4.4.6 and above

auto_trackSAAutoTrackTypeFull-Track collection type

Default is not enabled

START: Application startup
END: Application exit
CLICK: Click event
VIEW_SCREEN: Page view
Example: If you need to collect startup and exit events, you need to set SAAutoTrackType.START|SAAutoTrackType.END
To collect all, you need to set
SAAutoTrackType.START|SAAutoTrackType.END|SAAutoTrackType.CLICK|SAAutoTrackType.VIEW_SCREEN

flush_intervalintSet the minimum interval between two eventsDefault 15 seconds, minimum 5 seconds, in milliseconds
flush_bulksizeintSet the maximum number of items that trigger flush in local cacheDefault 100, minimum 50
encryptbooleanWhether to enable encryptionDefault false, only support RSA+AES
javascript_bridgebooleanWhether to support H5 integrationDefault false

android

object

Android Specific Configuration

  • sub_process_flush: Whether to support data reporting from sub-processes
  • jellybean: Whether to support API level 16 and below
  • max_cache_size: Maximum cache size

android:{

    sub_process_flush:true, //default is false

    jellybean:true ,                 //default is false

    max_cache_size:48 * 1024*1024      //unit is byte, default is 32 * 1024 * 1024

}

iosobject

iOS Specific Configuration

  • max_cache_size: Maximum cache size in units of records

ios:{

    max_cache_size:10000   default is 10000 records

}

visualizedobject

Visualization Related Configuration

  • auto_track: boolean Whether to enable auto track
  • properties:Whether custom attributes are available

visualized{

    auto_track:true, default false

    properties:true   default false

heat_mapboolean

Click map switch

heat_map:true  default false

If the App has compliance requirements, you can refer to React Native Compliance Steps.

If you initialize on ReactNative, you don't need to initialize it again on Android and iOS

5. Cautions

If the Sensors Analytics SDK RN module 1.1.8 or earlier versions were previously used in the project and full tracking was enabled, please turn off the previously enabled full tracking content after upgrading to the latest version, otherwise the same App element click event will be collected twice.

  1. Android:
    • Remove the call to the enableReactNativeAutoTrack() method
  2. iOS:
    • For developers who directly integrate the source code, you need to delete SENSORS_ANALYTICS_REACT_NATIVE=1 from the compilation option Preprocessor Macros.
      (For projects that directly integrate the SDK project, you need to modify the compilation options in the corresponding project of the SDK, and delete SENSORS_ANALYTICS_REACT_NATIVE=1 in Preprocessor Macros).


    • For using Cocoapods Developers who integrate the analytics SDK,在 pod 'SensorsAnalyticsSDK' delete :subspecs => ['ENABLE_REACT_NATIVE_APPCLICK'].