DCR React Native WebView Integration

From Engineering Client Portal

Revision as of 21:22, 18 May 2020 by ColinBrown (talk | contribs) (Created page with "{{Breadcrumb|}} {{Breadcrumb|Digital}} {{Breadcrumb|International}} {{CurrentBreadcrumb}} Category:Digital <br/> <b>Related Topics :</b> <br/> [http://eng-client-portal-n...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Engineering Portal breadcrumbArrow.png Digital breadcrumbArrow.png International breadcrumbArrow.png DCR React Native WebView Integration

Related Topics :
Integrate Nielsen SDK Simplified Api in React-Native App
Integrate Nielsen SDK Legacy Api in React-Native App

Integrate Nielsen SDK in React-Native Webview App

Overview

The Nielsen SDK is one of multiple framework SDKs that Nielsen provides to enable measuring linear (live) and on-demand TV viewing using TVs, mobile devices, etc. The App SDK is the framework for mobile application developers to integrate Nielsen Measurement into their media player applications. It supports a variety of Nielsen Measurement Products like Digital in TV Ratings, Digital Content Ratings (DCR & DTVR), and Digital Ad Ratings (DAR). Nielsen SDKs are also equipped to measure static content and can track key life cycle events of an application like:

  • Application launch events and how long app was running
  • Time of viewing a sub section / page in the application.

This guide will show how to use the Nielsen SDK in React Native Webview applications on Android and iOS devices.
We will not go into detail about what React Native is or how to create Apps with this Framework. If you are looking for information on this, please read the React-Native documentation.

Note : Support for React-native in Nielsen SDK is available from version 7.2.0.0

Prerequisites

To start using the App SDK, the following details are required:

  • App ID (appid): Unique ID assigned to the player/site and configured by product.
  • sfcode: Unique identifier for the environment that the SDK should point to.
  • Nielsen SDK: The Nielsen SDK package contains a variety of sample players for your reference.

If you do not have any of these prerequisites or if you have any questions, please contact our SDK sales support team. Refer to Digital Measurement Onboarding guide for information on how to get a Nielsen App SDK and appid.

For more detail on the native SDKs please refer to the App integration guides available on this portal.

Implementation

This guide covers implementation covers

  • the implementation of React-Native bridge (NielsenAppSDKJSHandlerBridge) for iOS and Android
  • the usage of the exposed Javascript API

What we will not cover is the general setup of React-Native applications. If you are new to React-Native please refer to React-Native for documentation.

For simplicity we have focused on implementing a single instance of the Nielsen SDK. Should there be the need for multiple instances developers have to add some logic for that.

Setting up your Environment

   iOS

The first step is to ensure that the following frameworks and libraries are imported into the Frameworks folder of the iOS Xcode project before working with the Nielsen SDK.

  • UIKit.framework
  • Foundation.framework
  • AdSupport.framework
  • SystemConfiguration.framework
  • Security.framework
    • Nielsen Analytics framework makes use of a number of functions in this library.
  • AVFoundation.framework
    • This framework is mandatory for the iOS SDK version 5.1.1 to work.
  • CoreLocation.framework (Not applicable for International (Germany))
  • CoreMedia.framework
  • NielsenAppApi.framework

Nielsens App SDK is compatible with Apple iOS versions 9.0 and above.


   Android

The first step is to add the AppSdk.jar library that runs on the Android’s Dalvik Virtual Machine to the libs folder (might have to be created) for the Android part of your project.

Note : Please make sure that you get Android X enabled appsdk.jar from nielsen.

android/app/libs

The next step is to add the following permissions on the project’s AndroidManifest.xml file.

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:required="false" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

For more details to handle runtime permissions in Android versions, please visit [1].
Nielsen SDK uses google play services library. Hence add the below gradle dependency in your project's build.gradle file

    implementation 'com.google.android.gms:play-services:+'
  • App SDK checks to see if there is a Google service available and updated.
  • If not available or updated, App SDK will not use this service when executing its functions and will make reference to missing imports and the app will not be compiled.

Library

Nielsen App SDK uses the following packages/classes from the Google Play service.

  • google-play-services_lib

Classes/package

  • com.google.android.gms.ads.identifier.AdvertisingIdClient;
  • com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
  • com.google.android.gms.common.ConnectionResult;
  • com.google.android.gms.common.GooglePlayServicesUtil;
  • com.google.android.gms.common.GooglePlayServicesRepairableException;
  • com.google.android.gms.common.GooglePlayServicesNotAvailableException;

Creating React-Native bridge (NielsenAppSDKJSHandlerBridge) for the Nielsen SDK

In order to be able to use Nielsens native SDKs React-Native bridges have to be implemented and added to the iOS and Android projects. The following shows implementations for both platforms, that provide the basic methods to start measuring the app. The source code can be copied from below to provide an easy start.

Please refer to the integration guides for Nielsens native SDKs to get a deeper understanding of the technical detail.

iOS

The iOS implementation of the bridge module consists of two files, a header and an implementation file.

Objective-c

The implementation of the bridge module consists of two files, a header and an implementation file, written in Objective-c. These two files need to be added to the iOS XCode project.

The header file is NielsenAppSDKJSHandlerBridge.h

// Copyright <2020> <The Nielsen Company>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>

@interface NielsenAppSDKJSHandlerBridge : RCTEventEmitter <RCTBridgeModule>
@end


The actual implementation of the module happens in NielsenAppSDKJSHandlerBridge.m

// Copyright <2020> <The Nielsen Company>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#import "NielsenAppSDKJSHandlerBridge.h"
#import "NielsenSDKImport.h"

@interface NielsenAppSDKJSHandlerBridge()

@property (strong) NielsenAppSDKJSHandler* jsEventHandler;

@end

@implementation NielsenAppSDKJSHandlerBridge
  RCT_EXPORT_MODULE();

- (NSArray<NSString *> *)supportedEvents
{
  return @[@"NielsenSDKMsg"];
}


RCT_EXPORT_METHOD(create:(NSString *)apiType)
{
  @synchronized (self) {
    if (!self.jsEventHandler) {
        NSLog(@"NielsenAppSDKJSHandlerBridge: create: %@", apiType);
        self.jsEventHandler = [[NielsenAppSDKJSHandler alloc] initWithApiType:apiType];
    }
  }
}

RCT_EXPORT_METHOD(nielsenSDKMsg:(NSString *)message)
{
  @synchronized (self) {
    if (self.jsEventHandler) {
        NSLog(@"NielsenAppSDKJSHandlerBridge: %@", message);
        [self.jsEventHandler jsEventEmitter:self didReceiveScriptMessage:message];
    }
  }
}

RCT_EXPORT_METHOD(free)
{
  @synchronized (self) {
    NSLog(@"NielsenAppSDKJSHandlerBridge: free");
    self.jsEventHandler = nil;
  }
}

@end
Swift

The implementation of the bridge module consists of two files, a header file, written in Objective-c and an implementation file, written in Swift. These two files need to be added to the iOS XCode project.

The header file is NielsenAppSDKJSHandlerBridge.m

// Copyright <2020> <The Nielsen Company>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#import "React/RCTBridgeModule.h"
#import "React/RCTEventEmitter.h"

@interface RCT_EXTERN_MODULE(NielsenAppSDKJSHandlerBridge, RCTEventEmitter)

RCT_EXTERN_METHOD(create:(NSString *)apiType)
RCT_EXTERN_METHOD(nielsenSDKMsg:(NSString *)message)
RCT_EXTERN_METHOD(free)

@end


The actual implementation of the module happens in NielsenAppApiBridge.swift

// Copyright <2020> <The Nielsen Company>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import Foundation
import NielsenAppApi

@objc(NielsenAppSDKJSHandlerBridge)
class NielsenAppSDKJSHandlerBridge: RCTEventEmitter {

  private var jsEventHandler: NielsenAppSDKJSHandler? = nil

  // we need to override this method and
  // return an array of event names that we can listen to
  override func supportedEvents() -> [String]! {
    return ["NielsenSDKMsg"]
  }

  @objc
  func create(_ apiType: String) {
    NSLog("NielsenAppSDKJSHandlerBridge: %@ create: %@", self.jsEventHandler ?? "(null)", apiType);
    if jsEventHandler == nil {
      jsEventHandler = NielsenAppSDKJSHandler(apiType: apiType)
    }
  }

  @objc
  func nielsenSDKMsg(_ message: String) {
    NSLog("NielsenAppSDKJSHandlerBridge: %@ nielsenSDKMsg: %@", self.jsEventHandler ?? "(null)", message);
    jsEventHandler?.jsEventEmitter(self, didReceiveScriptMessage: message)
  }

  @objc
  func free() {
    NSLog("NielsenAppSDKJSHandlerBridge: %@ free", self.jsEventHandler ?? "(null)");
    jsEventHandler = nil
  }

  // RN warning fix
  @objc
  override static func requiresMainQueueSetup() -> Bool {
      return false
  }
  
}

Android

The Android implementation of the bridge module consists of two files, an implementation of a NielsenPackage to announce the actual module and the implementation of NielsenAppSDKJSHandlerBridge itself. The implementations have been put into the Java package

com.nielsen.app.react

The package implementation is in com/nielsen/app/react/NielsenPackage.java

// Copyright <2018> <The Nielsen Company>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package com.nielsen.app.react;

import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.ReactPackage;
import com.facebook.react.uimanager.ViewManager;
import com.nielsen.app.react.NielsenReactBridge;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 */
public class NielsenPackage implements ReactPackage {

    /**
     * Override createNativeModules to return our bridge module
     */
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        modules.add(new NielsenAppSDKJSHandlerBridge(reactContext));

        return modules;
    }

    /**
    */
    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

com/nielsen/app/react/NielsenAppSDKJSHandlerBridge.java

// Copyright <2018> <The Nielsen Company>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package com.nielsen.app.react;

import android.content.Context;
import android.util.Log;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.nielsen.app.sdk.AppSdk;
import com.nielsen.app.sdk.AppLaunchMeasurementManager;
import com.nielsen.app.sdk.NielsenAppSDKJSHandler;
import org.json.JSONObject;
import org.json.JSONException;
import java.util.Date;
import java.util.HashMap;

/**
 * NielsenAppSDKJSHandlerBridge is the class briding between react JS code
 * and the native Nielsen SDK.
 */
public class NielsenAppSDKJSHandlerBridge extends ReactContextBaseJavaModule {
    
    Context mContext;
    NielsenAppSDKJSHandler nielsenJSHandler;
    private static final String NIELSEN_TAG = "NielsenAppSDKRNBridge";
    private static final String RESULT_KEY = "result";
    private static final String ACTION_KEY = "action";
    private static final String ID_KEY = "id";
    private static final String PAYLOAD_KEY = "payload";
    private static final String DATA_KEY = "data";
    private static final String EVENT_KEY = "event";
    private static final String VALUE_KEY = "value";
    //Event Names emitted from native android code to RN
    public static final String EVENT_JS_HANDLER_RESULT = "NielsenSDKMsg";                              
    
    private static final String OPTOUT_URL = "optouturl";
    private static final String OPTOUT_STATUS = "optoutstatus";
    private static final String METER_VERSION = "meterversion";
    private static final String DEMOGRAPHIC_ID = "demographicid";

    /**
     * Constructor for the NielsenAppSDKJSHandlerBridge
     * Adds the new instance as LifeCycleEventListener for conttex
     * @param context  The react application context
     */
    public NielsenAppSDKJSHandlerBridge(ReactApplicationContext context) {
        super(context);
        mContext = context.getApplicationContext();;
        nielsenJSHandler = null;
    }

    /**
     * Implements getName method from ReactContextBaseJavaModule
     * @return  The constant string 'NielsenAppSDKJSHandlerBridge'
     */
    @Override
    public String getName() {
        return "NielsenAppSDKJSHandlerBridge";
    }

    @ReactMethod
    public void create(String apiType) {
       if(apiType != null)
       {
        if(mContext != null)
        {
            nielsenJSHandler = new NielsenAppSDKJSHandler(mContext,apiType);
        }
        else
        {
            Log.e(NIELSEN_TAG, "Context is null");
        }
       }     
    }

    /**
     * This function is responsible to process message received from BSDK
     * @param obj An instance of json string containing
     * meta data
     */
    @ReactMethod
    public void nielsenSDKMsg(String jsonStr) {
            try {
                if (nielsenJSHandler == null)
                {
                    Log.e(NIELSEN_TAG, "NielsenAppSDKJSHandler instance creation failed");
                }
                else 
                {
                    if(jsonStr != null && !jsonStr.isEmpty())
                    {
                        String result = nielsenJSHandler.postMessage(jsonStr);
                        String event = getEventFromMessage(jsonStr);
                        emitEvent(EVENT_JS_HANDLER_RESULT, "'"+result+"'");
                    }
                }
            }
            catch(Exception ex) {
                Log.e(NIELSEN_TAG, "Exception in nielsenSDKMsg : "+ex.getLocalizedMessage());
            }
    }

    @ReactMethod
    public void free() {
        if(nielsenJSHandler != null)
        {
            nielsenJSHandler.close();
        }
    }

    JSONObject getResultForMessage(String jsonStr, String resultStr) {
        JSONObject result = new JSONObject();
        if(jsonStr != null)
        {
           try {
            JSONObject jsonMsg = readableMapToJSONObject(jsonStr);
            if(jsonMsg.has(PAYLOAD_KEY))
            {
                JSONObject payload = jsonMsg.getJSONObject(PAYLOAD_KEY);
                payload.remove(DATA_KEY);
                payload.put(RESULT_KEY, resultStr);
            }
           
           result = jsonMsg;
          }
          catch(Exception ex) {
             Log.e(NIELSEN_TAG, "Exception in getResultForMessage "+ex.getLocalizedMessage());
          }
        }
        return result; 
    }

    String getEventFromMessage(String jsonStr) {
        String result = null;
        if(jsonStr != null)
        {
           try 
           {
            JSONObject jsonMsg = readableMapToJSONObject(jsonStr);
            if(jsonMsg.has(ACTION_KEY))
            {
                String action = jsonMsg.getString(ACTION_KEY);
                JSONObject payload = jsonMsg.getJSONObject(PAYLOAD_KEY);
                if(payload.has(DATA_KEY))
                {
                    JSONObject data = payload.getJSONObject(DATA_KEY);
                    if(data.has(EVENT_KEY))
                    {
                        result = data.getString(EVENT_KEY);
                    }    
                }    
            }
          }
          catch(Exception ex) {
             Log.e(NIELSEN_TAG, "Exception in getEventFromMessage "+ex.getLocalizedMessage());
          }
        }
        return result; 
    }

    String getIdFromMessage(String jsonStr) {
        String result = null;
        if(jsonStr != null)
        {
           try 
           {
            JSONObject jsonMsg = readableMapToJSONObject(jsonStr);
            if(jsonMsg.has(PAYLOAD_KEY))
            {
               
                JSONObject payload = jsonMsg.getJSONObject(PAYLOAD_KEY);
                if(payload.has(ID_KEY))
                {
                    result = payload.getString(ID_KEY); 
                }    
            }
          }
          catch(Exception ex) {
             Log.e(NIELSEN_TAG, "Exception in getIdFromMessage "+ex.getLocalizedMessage());
          }
        }
        return result; 
    }

    /**
     * Emit's the event to React-native code
     * Needs to be cached in JS
     */   
    public void emitEvent(String eventName, String params) {
        if (null != params) {
            getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
        }
    }
    /**
     * Static method to convert json string to JSONObject instances
     * (used by the Nielsen SDK)
     * @param jsonStr  JSON string metadata to be converted
     * @return     An instance of JSONObject containing the mapped JS object
     *             values (if successful, empty otherwise)
     */
    static private JSONObject readableMapToJSONObject(String jsonStr) {
        JSONObject ret = null;;
        try {
            ret = new JSONObject(jsonStr);
        }
        catch (JSONException ex) {
            Log.e(NIELSEN_TAG, "Exception in readableMapToJSONObject "+ex.getMessage());
        }

        return ret;
    }
}


The package needs to be provided in the getPackages method of the MainApplication.java file. This file exists under the android folder in your react-native application directory. The path to this file is: android/app/src/main/java/com/your-app-name/MainApplication.java.

import com.nielsen.app.react.NielsenPackage;   //<-- Import the package in MainApplication.java
//...

    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
                //...,
                new NielsenPackage()); // <-- Add the bridge package to the getPackages method.
    }

In order to import the bridges into the Javascript context please add below import statement in java script code

import { NativeModules } from 'react-native'

NielsenAppSDKJSHandlerBridge Initialization

NielsenAppSDKJSHandlerBridge class needs to be initialised in java script context. You can initialise NielsenAppSDKJSHandlerBridge either for GGPM or TrackEvent api type. To initialise NielsenAppSDKJSHandlerBridge for TrackEvent you need to pass string as "trackEvent" to create() api and empty for GGPM.

It will be advisable to initialise the NielsenAppSDKJSHandlerBridge once in constructor of component.

Sample Initialization Code

    import NativeModules from 'react-native';
    
    //Initialization with GGPM Api type 
    NativeModules.NielsenAppSDKJSHandlerBridge.create("");
    
    
    //Initialization with TrackEvent Api type 
    NativeModules.NielsenAppSDKJSHandlerBridge.create("trackEvent");

NielsenAppSDKJSHandlerBridge Error Console Messages

To view the Error and Event codes for iOS and Android, please review the App SDK Event Code Reference page.

Enable Javascript for React-Native-Webview

Please make sure that you enable java script on webview. To enable the java script code in webview we need to set javaScriptEnabled={true} like below

 
 <WebView
        source={testUri}
        javaScriptEnabled={true}
      />

Notify BSDK about running in React-Native-Webview

To enable the communication between Webview and BSDK please make sure that we inject below java script code in webview before loading url. In below java script code we set NielsenAppSDKJSHandler to true and while loading BSDK detects this variable and prepares himself for react native.

 //Mandatory java script to be injected in webview
 const enableNielsenHandler = `window.NielsenAppSDKJSHandler = true; true;`;
 
 <WebView
        useWebKit={true}
        source={testUri}
        ref={r => (this.mWebView = r)}
        javaScriptEnabled={true}
        injectedJavaScriptBeforeContentLoaded={enableNielsenHandler}
        onLoadStart={syntheticEvent => {
          this.mWebView.injectJavaScript(enableNielsenHandler);
        }}
      />

Note :Please make sure that you inject the above java script block as it is otherwise BSDK will not be able to send messages to APPSDK.

Listen to BSDK messages in React-Native

We can listen to BSDK messages with onMessage property of webview and forward them to NielsenAppSDKJSHandlerBridge like below sample code. We have function nielsenSDKMsg() inside NielsenAppSDKJSHandlerBridge which accepts string message from BSDK.

 
 <WebView
        source={testUri}
        ref={r => (this.mWebView = r)}
        onMessage={event => {
          try {
            NativeModules.NielsenAppSDKJSHandlerBridge.nielsenSDKMsg(event.nativeEvent.data);
          } catch (e) {
            console.log(TAG + 'onMessage error: ' + e);
          }
        }}
      />

Listen to response from NielsenAppSDKJSHandlerBridge

As we know that java script code and react native bridge communicates with each other in asynchronous way. Hence we can receive response from NielsenAppSDKJSHandlerBridge by listening to events dispatched as below.

Note :Please make sure that we forward response received from NielsenAppSDKJSHandlerBridge to BSDK.

 
    const nielsenNativeMsg = new NativeEventEmitter(NativeModules.NielsenAppSDKJSHandlerBridge);
    nielsenNativeMsg.addListener('EVENT_JS_HANDLER_RESULT', data => {
      webview.injectJavaScript('window.postMessage(' + data.result + ", '*');");
    });