How to Integrate the Device Data Collector into React Native Applications

To integrate the Mobile SDKs into a hybrid React Native application, there are three main steps:

  1. iOS Integration

  2. Android Integration

  3. Platform Selection Integration

Integrating the Device Data Collector iOS SDK to React Native Hybrid Apps

Provide native support for your solution by integrating the iOS SDK into your React Native application. This allows you to use our services without having to create API calls.

To integrate the iOS SDK into React Sative apps, create a wrapper around the iOS SDK and then integrate it in each native project.

Integration Steps for iOS (include SDK in project)

There are three ways to integrate the iOS SDK with React Native App:

Integration Steps for iOS (create wrapper)

Setup

  1. Open the iOS project within your React Native application in Xcode.

  2. In Finder, go to the project folder, iOS folder, and then open .xcworkspace (if pods)/.xcodeproj.

Objective-C

  1. Import KDataCollector.h and KountAnalyticsViewController.h in AppDelegate.h

  2. Add the following code in the Appdelegate.m file.

        
        [[KDataCollector sharedCollector] setDebug:YES];
        // TODO Set your Merchant ID
        [[KDataCollector sharedCollector] setMerchantID:@"900900"];
        // TODO Set the location collection configuration
        [[KDataCollector sharedCollector]setLocationCollectorConfig:KLocationCollectorConfigRequestPermission];
        // For a released app, you'll want to set this to KEnvironmentProduction
        [[KDataCollector sharedCollector] setEnvironment:KEnvironmentTest];
        [[KountAnalyticsViewController sharedInstance] setEnvironmentForAnalytics: 
                    [KDataCollector.sharedCollector environment]];
        
  3. Create a new file called KountBridgeModule.h and add the following code.

        #import <React/RCTBridgeModule.h>
        #import "KDataCollector.h"
        #import "KountAnalyticsViewController.h"
        
        @interface KountBridgeModule: NSObject <RCTBridgeModule>
        -(void) collect;
        @end
        
  4. Create the implementation file KountBridgeModule.m in the same folder as the .h file and add the following code.

       
        #import "KountBridgeModule.h"
         @implementation KountBridgeModule
        
            RCT_EXPORT_MODULE(KountBridgeModule);
            RCT_EXPORT_METHOD(collect){
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSString *sessionID = nil;
        
                    // By default set analyticsSwitch to false
                    [[KountAnalyticsViewController sharedInstance] collect:sessionID analyticsSwitch:false 
                    completion:^(NSString * _Nonnull sessionID, BOOL success, NSError * 
                           _Nullable error) {
                           if(success) {
                                   NSLog(@"Collection Successful");
                           }
                           else {
                                   if (error != nil) {
                                   NSLog(@"Collection failed with 
                           error:%@",error.description);
                               }
                               else {
                                   NSLog(@"Collection failed without error");
                               }
                      }
                }];
           });
        }
        
        RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getAppID) {
            NSString *sessionID = [KountAnalyticsViewController getAppSessionID];
            return sessionID;
        }
        
        @end
        

Swift

  1. Import KDataCollector.h and KountAnalyticsViewController.h in <ProjectName>-Bridging-Header.h.

  2. Add the following code in the Appdelegate.swift file.

        // Set the location collection configuration
        KDataCollector.shared().locationCollectorConfig = KLocationCollectorConfig.requestPermission
            KDataCollector.shared().debug = true
            // Set your Merchant ID
            KDataCollector.shared().merchantID = "900900"
            // For a released app, you'll want to set this to KEnvironmentProduction
            KDataCollector.shared().environment = KEnvironment.test
            KountAnalyticsViewController().setEnvironmentForAnalytics(KDataCollector.shared().environment)
        
  3. Create a new file called KountBridgeModule.swift and add the following code.

        import UIKit
        
        @objc(KountBridgeModule)
        
        class KountBridgeModule: NSObject {
        
        @objc
        func collect() {
          DispatchQueue.main.async {
            KountAnalyticsViewController().collect(KountAnalyticsViewController.getAppSessionID(), analyticsSwitch: false) {
                (sessionID, success, error) in
                    if (success) {
                        print("IDK",KountAnalyticsViewController.getAppSessionID())
                        print("Collection Successful")
                    }
                    else {
                        if((error) != nil) {
                            print("Collection failed with error",error?.localizedDescription as Any)
                        }
                        else {
                            print("Collection failed without error")
                        }
                }
            }
          }
  4. Create a new file called KountBridgeModule.m and add the following code to make native code access available to .js files.

        #import <Foundation/Foundation.h>
        #import "React/RCTBridgeModule.h"
        
         @interface RCT_EXTERN_MODULE(KountBridgeModule, NSObject)
         
         RCT_EXTERN_METHOD(collect)
        + (BOOL)requiresMainQueueSetup
        {
            return YES;
        }
        
        RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getAppID) {
                                    NSString *sessionID = [KountAnalyticsViewController getAppSessionID];
                                    return sessionID;
                           }
        
         @end
        

Integrating the Device Data Collector Android SDK to React Native Hybrid Apps

Integrate the Android SDK into your React Native application to collect additional end-user information. This assists in detecting suspicious devices and preventing fraud.

Integration steps for Android (include in project)

You have two project integration options. Choose the one that best fits your project. We recommend using the Gradle option if you do not have a preference.

Note

If android:allowbackup attribute is false in your <application> tag, add tools:replace="android:allowBackup" to your application tag.

Integration steps for Android (create wrapper)

  1. In the main activity of your application, initialize the collector and assign the <MERCHANT_ID> you received. Optionally, you can provide a sessionID if you need to generate your own. If not, the SDK will generate one for you. Send this sessionID back to your severs in order to make calls to the API.

    Add the following code in your MainActivity:

        import com.kount.api.analytics.AnalyticsCollector;
        import com.kount.api.analytics.AnalyticsConstants;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
          ...
          // REQUIRED SECTION
          AnalyticsCollector.setMerchantId("999999");
          // END REQUIRED SECTION
          AnalyticsConstants.collectDeviceDataForSession=true
      
          //For production need to add AnalyticsCollector.ENVIRONMENT_PRODUCTION
          AnalyticsCollector.setEnvironment(AnalyticsCollector.ENVIRONMENT_TEST);
      
          // OPTIONAL SESSION_ID SECTION
          final String deviceSessionID UUID.randomUUID().toString();
          AnalyticsCollector.setSessionId(deviceSessionID);
          // END OPTIONAL SESSION_ID SECTION
          ...
         }
        
  2. To support Location Collection in Android API 23 and later, add the following permissions to your main activity, onCreate method:

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
          if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, AnalyticsCollector.REQUEST_PERMISSION_LOCATION);
          } else {
              ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, AnalyticsCollector.REQUEST_PERMISSION_LOCATION);
          }
        }
        

    Note

    While preferred, not all apps are approved in the app store to use the ACCESS_FINE_LOCATION. If your app has been rejected for having this permission, replace ACCESS_FINE_LOCATION (uses GPS) with ACCESS_COARSE_LOCATION (uses cellular triangulation).

  3. Create the KountModule.java file inside of the android/app/src/main/java/com/your-app-name/ folder. This file contains your native module Java class.

    Add the following code:

        import androidx.annotation.NonNull;
        import com.facebook.react.bridge.ReactApplicationContext;
        import com.facebook.react.bridge.ReactContextBaseJavaModule;
        import com.facebook.react.bridge.ReactMethod;
        import com.kount.api.analytics.AnalyticsCollector;
    
        public class KountModule extends ReactContextBaseJavaModule {
          private static ReactApplicationContext reactContext;
      
          KountModule(ReactApplicationContext context) {
              super(context);
              reactContext = context;
          }
      
          @ReactMethod
          public void collect() {
              AnalyticsCollector.collectDeviceDataForSession(reactContext,(sessionId)->
    {
      Log.d("TAG", "Client success completed with sessionId "+sessionId);
      Log.d("TAG", "DDC status is " +AnalyticsCollector.getCollectionStatus());
      callback.invoke(sessionId,AnalyticsCollector.getCollectionStatus().name());
      return null;
    },(sessionId, error)->
      {
        Log.d("TAG", "client failed with sessionId $error, $sessionId");
        Log.d("TAG", "DDC status is " +AnalyticsCollector.getCollectionStatus());
        callback.invoke(sessionId,AnalyticsCollector.getCollectionStatus().name());
        return null;
    });
          }
      
          @NonNull
          @Override
          public String getName() {
              return "KOUNT_MODULE";
          }
        }
        
  4. Register the Module: To add your Native Module to ReactPackage, first create a new Java Class named KountModulePackage.java that implements ReactPackage inside the android/app/src/main/java/com/your-app-name/ folder:

    Then add the following content:

        import androidx.annotation.NonNull;
    
        import com.facebook.react.ReactPackage;
        import com.facebook.react.bridge.NativeModule;
        import com.facebook.react.bridge.ReactApplicationContext;
        import com.facebook.react.uimanager.ViewManager;
        
        import java.util.ArrayList;
        import java.util.Collections;
        import java.util.List;
        
        public class KountModulePackage implements ReactPackage {
          @NonNull
          @Override
          public List<NativeModule> createNativeModules(@NonNull ReactApplicationContext reactContext) {
            List<NativeModule> modules = new ArrayList<>();
            modules.add(new KountModule(reactContext));
            return modules;
          }
        
          @NonNull
          @Override
          public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactContext) {
              return Collections.emptyList();
          }
        }
        
  5. Open your MainApplication.java file in the following path: android/app/src/main/java/com/your-app-name/MainApplication.java and locate the ReactNativeHost’s getPackages() method and add your package to the packages list.

        @Override
        protected List<ReactPackage> getPackages() { 
         @SuppressWarnings("UnnecessaryLocalVariable")   
         List<ReactPackage> packages = new PackageList(this).getPackages();  
         packages.add(new KountModulePackage()); 
         return packages;
        }
        
  6. Create a new JavaScript file named KountModule.js in your project root folder and add the following code.

          import { NativeModules } from "react-native";
          const {KOUNT_MODULE}=NativeModules;
          export default KOUNT_MODULE;
          

Platform Selection Integration in React Native App

Once both the Android and iOS portions of the SDK are set up, you can add the component to the React Native App.

  1. In the React Native application, go to App.js and add the following code.

        import React from 'react';
        import { Text, View, NativeModules, Platform } from 'react-native';
        import KOUNT_MODULE from './KountModule';
        import { Button } from 'react-native';
        import { Component } from 'react';
        
        const {KountBridgeModule} =  NativeModules;
        
  2. Review these examples for how to call the methods based on platforms. These methods are the onPress events of buttons.

        export default class App extends Component {
        
        /Platform specific code
        onPressCollect = () => {
          if (Platform.OS == 'ios') {
              console.log("Started");
              KountBridgeModule.collect();
          } else if (Platform.OS == 'android') {
              KOUNT_MODULE.collect();
          }
        }
         render() {
            return (
            <View style={{paddingTop: 50}}>
            <Button title="Collect" onPress={ this.onPressCollect} />
            </View>
            )
          }
        
        }
        
  3. Run the React Native app.

    It should capture the data points for the Device Data Collector in both iOS and Android platforms.

Was this article helpful?
0 out of 0 found this helpful