DCR React Native SimplifiedAPI Integration

From Engineering Client Portal

Engineering Portal / Digital / DCR & DTVR / DCR React Native SimplifiedAPI Integration

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

_

_

Integrate Nielsen SDK Simplified Api in React-Native 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 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 (NielsenEventTrackerBridge) 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 (NielsenEventTrackerBridge) 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.

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

import { NativeModules } from 'react-native'


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 NielsenEventTrackerBridge.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 NielsenEventTrackerBridge : RCTEventEmitter <RCTBridgeModule>
@end


The actual implementation of the module happens in NielsenEventTrackerBridge.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 "NielsenEventTrackerBridge.h"
#import "AppDelegate.h"
#import <NielsenAppApi/NielsenEventTracker.h>

static NSString *const TAG = @"NielsenEventTrackerBridge";

@interface NielsenEventTrackerBridge() <NielsenEventTrackerDelegate>

@property (nonatomic) NSMutableDictionary<NSString *, NielsenEventTracker *> *nlsSDKs;

@end


@implementation NielsenEventTrackerBridge
RCT_EXPORT_MODULE();

/**
 * Since we need to communicate the opt-out url to javascript via events
 * we need to implement the following method
 */
- (NSArray<NSString *> *)supportedEvents
{
  return @[@"EVENT_INIT", @"EVENT_OPTOUT_URL", @"EVENT_OPTOUT_STATUS", @"EVENT_DEMOGRAPHIC_ID", @"EVENT_METER_VERSION"];
}

/**
 * Creates SDK instance and passes on the provided metadata
 * appInfo is simply passed to initWithAppInfo since the SDK already
 * performs error checking
 */
RCT_EXPORT_METHOD(createInstance:(NSDictionary *)appInfo)
{
  NSLog(@"createInstance: %@", appInfo);

  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
      self.nlsSDKs = NSMutableDictionary.dictionary;
  });

  @synchronized (self) {
    NSMutableDictionary *bridgedInfo = [NSMutableDictionary dictionaryWithDictionary:appInfo];
    NSString *sdk_id = [NSString stringWithFormat:@"%lli", (long long)([[NSDate date] timeIntervalSince1970] * 1000)];

    bridgedInfo[kCfgNmPlayerId] = sdk_id;
    NielsenEventTracker *nlsSDK = [[NielsenEventTracker alloc] initWithAppInfo:bridgedInfo delegate:self];
        if (nlsSDK) {
      self.nlsSDKs[sdk_id] = nlsSDK;
      [self sendEventWithName:@"EVENT_INIT" body:@{@"id": sdk_id}];
    }
  }
}

/**
* Wrapper for the SDK's trackEvent method. The provided data is
* simply passed on
*/
RCT_EXPORT_METHOD(trackEvent:(NSString *)sdk_id :(NSDictionary *)data)
{
  NSLog(@"trackEvent: %@", data);

  if (self.nlsSDKs[sdk_id]) {
      [self.nlsSDKs[sdk_id] trackEvent:data];
  } else {
    NSLog(@"Error: instance %@ not found", sdk_id);
  }
}

/**
 * Destroying of SDK instance
 */
RCT_EXPORT_METHOD(free:(NSString *)sdk_id)
{
    NSLog(@"free: %@", sdk_id);

    if (self.nlsSDKs[sdk_id]) {
        self.nlsSDKs[sdk_id] = nil;
    } else {
      NSLog(@"Error: instance %@ not found", sdk_id);
    }
}

/**
 * Retrieves the demographic Id from the SDK instance and fires off the
 * EVENT_DEMOGRAPHIC_ID event, so the meter version can be captured
 */
RCT_EXPORT_METHOD(getDemographicId:(NSString *)sdk_id)
{
    NSLog(@"getDemographicId: %@", sdk_id);

    if (self.nlsSDKs[sdk_id]) {
        [self sendEventWithName:@"EVENT_DEMOGRAPHIC_ID" body:@{@"demographic_id": self.nlsSDKs[sdk_id].demographicId}];
    } else {
      NSLog(@"Error: instance %@ not found", sdk_id);
    }
}

/**
 * Retrieves the status from the SDK instance and fires off the
 * EVENT_OPTOUT_STATUS event, so the status can be captured
 */
RCT_EXPORT_METHOD(getOptOutStatus:(NSString *)sdk_id)
{
    NSLog(@"getOptOutStatus: %@", sdk_id);

    if (self.nlsSDKs[sdk_id]) {
        [self sendEventWithName:@"EVENT_OPTOUT_STATUS" body:@{@"user_optout": [NSString stringWithFormat:@"%d", self.nlsSDKs[sdk_id].optOutStatus]}];
    } else {
      NSLog(@"Error: instance %@ not found", sdk_id);
    }
}

/**
 * Retrieves the url from the SDK instance and fires off the
 * EVENT_OPTOUT_URL event, so the url can be captured
 */
RCT_EXPORT_METHOD(userOptOutURLString:(NSString *)sdk_id)
{
    NSLog(@"userOptOutURLString: %@", sdk_id);

    if (self.nlsSDKs[sdk_id]) {
        [self sendEventWithName:@"EVENT_OPTOUT_URL" body:@{@"optouturl": self.nlsSDKs[sdk_id].optOutURL}];
    } else {
      NSLog(@"Error: instance %@ not found", sdk_id);
    }
}

/**
 * Retrieves the meter version from the SDK instance and fires off the
 * EVENT_METER_VERSION event, so the meter version can be captured
 */
RCT_EXPORT_METHOD(getMeterVersion:(NSString *)sdk_id)
{
    NSLog(@"getMeterVersion: %@", sdk_id);

    if (self.nlsSDKs[sdk_id]) {
        [self sendEventWithName:@"EVENT_METER_VERSION" body:@{@"meter_version": self.nlsSDKs[sdk_id].meterVersion}];
    } else {
      NSLog(@"Error: instance %@ not found", sdk_id);
    }
}

- (void)dealloc
{
  self.nlsSDKs = 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 NielsenEventTrackerBridge.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(NielsenEventTrackerBridge, RCTEventEmitter)

RCT_EXTERN_METHOD(createInstance:(NSDictionary *)appInfo)
RCT_EXTERN_METHOD(trackEvent:(NSString *)sdk_id :(NSDictionary *)data)
RCT_EXTERN_METHOD(free:(NSString *)sdk_id)
RCT_EXTERN_METHOD(getDemographicId:(NSString *)sdk_id)
RCT_EXTERN_METHOD(getOptOutStatus:(NSString *)sdk_id)
RCT_EXTERN_METHOD(userOptOutURLString:(NSString *)sdk_id)
RCT_EXTERN_METHOD(getMeterVersion:(NSString *)sdk_id)

@end


The actual implementation of the module happens in NielsenEventTrackerBridge.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(NielsenEventTrackerBridge)
class NielsenEventTrackerBridge: RCTEventEmitter, NielsenEventTrackerDelegate {

  private let TAG = "NielsenEventTrackerBridge"

  private var nlsSDKs: [String:NielsenEventTracker]? = nil

  override init()
  {
    super.init()
    
    self.nlsSDKs = [:]
  }

  deinit
  {
    nlsSDKs = nil
  }

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

  /**
  * Creates SDK instance and passes on the provided metadata
  * appInfo is simply passed to initWithAppInfo since the SDK already
  * performs error checking
  */
  @objc
  func createInstance(_ appInfo: Dictionary<String, Any>)
  {
    NSLog("createInstance: \(appInfo)")

    var bridgedInfo = appInfo
    let sdk_id = String(format: "%lli", CUnsignedLongLong(Date().timeIntervalSince1970 * 1000))

    bridgedInfo[kCfgNmPlayerId] = sdk_id
    let nlsSDK = NielsenEventTracker(appInfo: bridgedInfo, delegate: self)
    if nlsSDK != nil {
      self.nlsSDKs![sdk_id] = nlsSDK!
      self.sendEvent(withName: "EVENT_INIT", body: ["id": sdk_id])
    }
  }

  /**
  * Wrapper for the SDK's trackEvent method. The provided data is
  * simply passed on
  */
  @objc
  func trackEvent(_ sdk_id: String, _ data: Dictionary<String, Any>)
  {
    NSLog("trackEvent: \(data)")

    if self.nlsSDKs![sdk_id] != nil {
      self.nlsSDKs![sdk_id]?.trackEvent(data)
    } else {
      NSLog("Error: instance \(sdk_id) not found")
    }
  }

  /**
  * Destroying of SDK instance
  */
  @objc
  func free(_ sdk_id: String)
  {
    NSLog("free: \(sdk_id)")

    if self.nlsSDKs![sdk_id] != nil {
      self.nlsSDKs![sdk_id] = nil
    } else {
      NSLog("Error: instance \(sdk_id) not found")
    }
  }
  
  /**
  * Retrieves the demographic Id from the SDK instance and fires off the
  * EVENT_DEMOGRAPHIC_ID event, so the meter version can be captured
  */
  @objc
  func getDemographicId(_ sdk_id: String)
  {
    NSLog("getDemographicId: \(sdk_id)")

    if self.nlsSDKs![sdk_id] != nil {
      self.sendEvent(withName: "EVENT_DEMOGRAPHIC_ID", body: ["demographic_id": self.nlsSDKs![sdk_id]?.demographicId])
    } else {
      NSLog("Error: instance \(sdk_id) not found")
    }
  }

  /**
  * Retrieves the status from the SDK instance and fires off the
  * EVENT_OPTOUT_STATUS event, so the status can be captured
  */
  @objc
  func getOptOutStatus(_ sdk_id: String)
  {
    NSLog("getOptOutStatus: \(sdk_id)")

    if self.nlsSDKs![sdk_id] != nil {
      self.sendEvent(withName: "EVENT_OPTOUT_STATUS", body: ["user_optout": self.nlsSDKs![sdk_id]?.optOutStatus])
    } else {
      NSLog("Error: instance \(sdk_id) not found")
    }
  }

  /**
  * Retrieves the url from the SDK instance and fires off the
  * EVENT_OPTOUT_URL event, so the url can be captured
  */
  @objc
  func userOptOutURLString(_ sdk_id: String)
  {
    NSLog("userOptOutURLString: \(sdk_id)")

    if self.nlsSDKs![sdk_id] != nil {
      self.sendEvent(withName: "EVENT_OPTOUT_URL", body: ["optouturl": self.nlsSDKs![sdk_id]?.optOutURL])
    } else {
      NSLog("Error: instance \(sdk_id) not found")
    }
  }

  /**
  * Retrieves the meter version from the SDK instance and fires off the
  * EVENT_METER_VERSION event, so the meter version can be captured
  */
  @objc
  func getMeterVersion(_ sdk_id: String)
  {
    NSLog("getMeterVersion: \(sdk_id)")

    if self.nlsSDKs![sdk_id] != nil {
      self.sendEvent(withName: "EVENT_METER_VERSION", body: ["meter_version": self.nlsSDKs![sdk_id]?.optOutURL])
    } else {
      NSLog("Error: instance \(sdk_id) not found")
    }
  }

  // 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 NielsenEventTrackerBridge 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.NielsenEventTrackerBridge;
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 NielsenEventTrackerBridge(reactContext));

        return modules;
    }

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

com/nielsen/app/react/NielsenEventTrackerBridge.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.LifecycleEventListener;
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.ReadableArray;
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.NielsenEventTracker;
import com.nielsen.app.sdk.IAppNotifier;
import com.nielsen.app.sdk.AppLaunchMeasurementManager;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.Date;
import java.util.HashMap;

/**
 * NielsenEventTrackerBridge is the class briding between react JS code
 * and the Nielsen App SDK.
 */
public class NielsenEventTrackerBridge extends ReactContextBaseJavaModule
                                implements IAppNotifier {

    /**
    */
    Context mContext;
    private static final String NIELSEN_TAG = "NielsenTrackEventBridge";
    private static final String INSTANCE_PREFIX = "Instance_";
    private HashMap<String, NielsenEventTracker> mAppSdkInstances = new HashMap();

    private static final String ID_KEY = "id";
    private static final String OPTOUT_URL_KEY = "optouturl";
    private static final String METER_VERSION_KEY = "meter_version";
    private static final String APP_DISABLE_KEY = "app_disable";
    private static final String OPTOUT_STATUS_KEY = "user_optout";
    private static final String DEVICE_ID_KEY = "demographic_id";
    private static final String NIELSEN_ID_KEY = "nielsen_id";

    //Event Names emitted from native android code
    public static final String EVENT_INIT = "EVENT_INIT"; // {"id", "instance_id"}                              
    public static final String EVENT_OPTOUT_URL = "EVENT_OPTOUT_URL"; // {"optouturl", "optout page url"}                              
    public static final String EVENT_METER_VERSION = "EVENT_METER_VERSION"; // {"optouturl", "optout page url"}                              
    public static final String EVENT_APP_DISABLE = "EVENT_APP_DISABLE"; // {"optouturl", "optout page url"}                              
    public static final String EVENT_OPTOUT_STATUS = "EVENT_OPTOUT_STATUS"; // {"optouturl", "optout page url"}                              
    public static final String EVENT_DEVICE_ID = "EVENT_DEMOGRAPHIC_ID"; // {"optouturl", "optout page url"}                              
    public static final String EVENT_NIELSEN_ID = "EVENT_NIELSEN_ID";

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

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

    /**
     * Implements getName method from IAppNotifier
     */
    @Override
    public void onAppSdkEvent(long l, int i, String s) {}

    /**
     * Initializes the module for use
     * @param obj An instance of ReadableMap (mapped JS object) containing
     *            initialization meta data
     */
    @ReactMethod
    public void createInstance(final ReadableMap obj) {
            try {
                JSONObject appSdkConfig = convertMapToJson(obj);
                NielsenEventTracker mAppSdk = new NielsenEventTracker(getReactApplicationContext(), appSdkConfig, this);
                if (!mAppSdk.isValid())
                {
                    Log.e(NIELSEN_TAG, "SDK instance creation failed");
                }
                else 
                {
                    Log.d(NIELSEN_TAG, "SDK instance created successfully");
                    String id = String.valueOf(new Date().getTime());
                    mAppSdkInstances.put(id, mAppSdk);
                    WritableMap params = Arguments.createMap();
                    params.putString(ID_KEY, id);
                    emitEvent(EVENT_INIT, params);
                }
            }
            catch(Exception ex) {
                Log.e(NIELSEN_TAG, "SDK Init failed : "+ex.getLocalizedMessage());
            }
    }

    /**
     * Remove the sdk instance
     * @param id An instance id of object to be removed
     */
    @ReactMethod
    public void removeInstance(final String id) {
            try {
                if (id != null && mAppSdkInstances.containsKey(id))
                {
                    mAppSdkInstances.get(id).close();
                    mAppSdkInstances.remove(id);
                    Log.d(NIELSEN_TAG, "SDK instance closed successfully");
                }
                else 
                {
                    Log.e(NIELSEN_TAG, "SDK instance not exists for close operation.");
                }
            }
            catch(Exception ex) {
                Log.e(NIELSEN_TAG, "SDK instance close failed : "+ex.getLocalizedMessage());
            }
    }

    /**
     * Emit's the event to React-native code
     * Needs to be catched in JS
     */
    public void emitEvent(String eventName, WritableMap params) {
        if (null != params) {
            getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
        }
    }    

    /**
     * Static method to convert ReadableMap instances to JSONObject instances
     * (used by the Nielsen SDK)
     * @param obj   The ReadableMap instance to be converted
     * @return      An instance of JSONObject containing the mapped JS object
     *              values (if successful, empty otherwise)
     */
    static private JSONObject convertMapToJson(final ReadableMap obj) {

        JSONObject ret = new JSONObject();
        try {
            ReadableMapKeySetIterator it = obj.keySetIterator();
            while (it.hasNextKey()) {
                String key = it.nextKey();
                switch (obj.getType(key)) {
                    case Null:
                        ret.put(key, JSONObject.NULL);
                        break;
                    case Boolean:
                        ret.put(key, obj.getBoolean(key));
                        break;
                    case Number:
                        ret.put(key, obj.getDouble(key));
                        break;
                    case String:
                        ret.put(key, obj.getString(key));
                        break;
                    case Map:
                        ret.put(key, convertMapToJson(obj.getMap(key)));
                        break;
                    case Array:
                        ret.put(key, convertArrayToJson(obj.getArray(key)));
                        break;
                }
            }
        }
        catch (JSONException ex) {
            Log.e(NIELSEN_TAG, "Exception in convertMapToJson "+ex.getMessage());
        }

        return ret;
    }

    private static JSONArray convertArrayToJson(ReadableArray readableArray) throws JSONException {
        JSONArray array = new JSONArray();
        for (int i = 0; i < readableArray.size(); i++) {
            switch (readableArray.getType(i)) {
                case Null:
                    break;
                case Boolean:
                    array.put(readableArray.getBoolean(i));
                    break;
                case Number:
                    array.put(readableArray.getDouble(i));
                    break;
                case String:
                    array.put(readableArray.getString(i));
                    break;
                case Map:
                    array.put(convertMapToJson(readableArray.getMap(i)));
                    break;
                case Array:
                    array.put(convertArrayToJson(readableArray.getArray(i)));
                    break;
            }
        }
        return array;
    }

     /**
     * This function returns NielsenEventTracker instance for id from map
     * @param id An instance id of object
     */
    NielsenEventTracker getInstance(String id) {
        NielsenEventTracker result = null;
        try {
            if (id != null && mAppSdkInstances.containsKey(id))
            {
                result = mAppSdkInstances.get(id);
            }
            else 
            {
                Log.e(NIELSEN_TAG, "SDK instance not exists for id = "+id);
            }
        }
        catch(Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in getInstance() : "+ex.getLocalizedMessage());
        }

        return result;
    }
  
    /**
     * Wrapper for the Nielsen SDK play method. Simply forwards calls
     * to the SDK.
     * @param obj   ReadableMap instance containing the mapped JS meta
     *              data object, e.g. {channelName: 'channel name here'}
     */
    @ReactMethod
    public void trackEvent(final String id, final ReadableMap obj) {
        try {
            if (null != id && getInstance(id) != null) {
                JSONObject metadata = convertMapToJson(obj);
                getInstance(id).trackEvent(metadata);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in trackEvent "+ex.getMessage());
        }
    }

    /**
     * Wrapper for the Nielsen SDK loadMetadata method. Simply forwards calls
     * to the SDK.
     * @param obj   ReadableMap instance containing the mapped JS meta
     *              data object
     */
    @ReactMethod
    public void appDisableApi(final String id, final boolean disabled) {
        try {
            if (null != id && getInstance(id) != null) {
                getInstance(id).appDisableApi(disabled);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in appDisableApi "+ex.getMessage());
        }
    }

    /**
     * Wrapper to retrieve the optOutUrl from the Nielsen SDK.
     * Emits a "OptOutUrl" event with the url as payload.
     * Needs to be catched in JS
     */
    @ReactMethod
    public void userOptOutURLString(String id) {
        WritableMap params = Arguments.createMap();
        try {
            if (null != id && getInstance(id) != null) {
                params.putString(OPTOUT_URL_KEY, getInstance(id).userOptOutURLString());
                emitEvent(EVENT_OPTOUT_URL, params);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in optOutUrl "+ex.getMessage());
        }
    }

    /**
     * Wrapper to retrieve the optOutUrl from the Nielsen SDK.
     * Emits a "OptOutUrl" event with the url as payload.
     * Needs to be catched in JS
     */
    @ReactMethod
    public void getOptOutStatus(String id) {
        WritableMap params = Arguments.createMap();
        try {
            if (null != id && getInstance(id) != null) {
                params.putString(OPTOUT_STATUS_KEY, ""+getInstance(id).getOptOutStatus());
                emitEvent(EVENT_OPTOUT_STATUS, params);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in getOptOutStatus "+ex.getMessage());
        }
    }

    /**
     * Wrapper to retrieve the optOutUrl from the Nielsen SDK.
     * Emits a "OptOutUrl" event with the url as payload.
     * Needs to be catched in JS
     */
    @ReactMethod
    public void getNielsenId(String id) {
        WritableMap params = Arguments.createMap();
        try {
            if (null != id && getInstance(id) != null) {
                params.putString(NIELSEN_ID_KEY, getInstance(id).getNielsenId());
                emitEvent(EVENT_NIELSEN_ID, params);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in optOutUrl "+ex.getMessage());
        }
    }

    /**
     * Wrapper to retrieve the optOutUrl from the Nielsen SDK.
     * Emits a "OptOutUrl" event with the url as payload.
     * Needs to be catched in JS
     */
    @ReactMethod
    public void getDemographicId(String id) {
        WritableMap params = Arguments.createMap();
        try {
            if (null != id && getInstance(id) != null) {
                String demographicId = getInstance(id).getDemographicId();
                params.putString(DEVICE_ID_KEY, demographicId);
                emitEvent(EVENT_DEVICE_ID, params);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in getDemographicId "+ex.getMessage());
        }
    }

    @ReactMethod
    public void getMeterVersion(String id) {
        WritableMap params = Arguments.createMap();
        try {
                params.putString(METER_VERSION_KEY,NielsenEventTracker.getMeterVersion());
                emitEvent(EVENT_METER_VERSION, params);
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in getMeterVersion "+ex.getMessage());
        }
    }

    @ReactMethod
    public void getAppDisable(String id) {
        WritableMap params = Arguments.createMap();
        try {
            if (null != id && getInstance(id) != null) {
                params.putString(APP_DISABLE_KEY, ""+getInstance(id).getAppDisable());
                emitEvent(EVENT_APP_DISABLE, params);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in getAppDisable "+ex.getMessage());
        }
    }

    @ReactMethod
    public void setDebug(char debugState) {
        try {
            NielsenEventTracker.setDebug(debugState);
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in setDebug "+ex.getMessage());
        }
    }

    @ReactMethod
    public void suspend(String id) {
        try {
            if (null != id && getInstance(id) != null) {  
                getInstance(id).suspend();
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in suspend "+ex.getMessage());
        }
    }

    @ReactMethod
    public void appInBackground(String id) {
        try {
            if (null != id && getInstance(id) != null) {  
                getInstance(id).appInBackground(mContext);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in appInBackground "+ex.getMessage());
        }
    }

    @ReactMethod
    public void appInForeground(String id) {
        try {
            if (null != id && getInstance(id) != null) {  
                getInstance(id).appInForeground(mContext);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in appInForeground "+ex.getMessage());
        }
    }

    @ReactMethod
    public void free(String id) {
        try {
            if (null != id && getInstance(id) != null) {  
                getInstance(id).close();
                mAppSdkInstances.remove(id);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in appInForeground "+ex.getMessage());
        }
    }

}


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'

Receiving responses from React-Native bridge

Due to the limitation that native methods can't return values directly, Javascript code must provide listeners for asynchronous React-Native bridge events.

  const eventEmitter = new NativeEventEmitter(NativeModules.NielsenEventTrackerBridge);

  var initListner = eventEmitter.addListener(
    "EVENT_INIT",
    (data) => {
      sdk_id = data.id;
      console.log("SDK initialized with id :" + data.id);
    }
  );
  var optoutUrlListner = eventEmitter.addListener(
    "EVENT_OPTOUT_URL",
    (data) => {
       console.log("EVENT_OPTOUT_URL :" + data.optouturl);
    }
  );
  var optoutStatusListner = eventEmitter.addListener(
    "EVENT_OPTOUT_STATUS",
    (data) => {
       console.log("EVENT_OPTOUT_STATUS :" + data.user_optout);
    }
  );
  var demographicIdListner = eventEmitter.addListener(
    "EVENT_DEMOGRAPHIC_ID",
    (data) => {
       console.log("EVENT_DEMOGRAPHIC_ID :" + data.demographic_id);
    }
  );
  var meterVersionListner = eventEmitter.addListener(
    "EVENT_METER_VERSION",
    (data) => {
       console.log("EVENT_METER_VERSION :" + data.meter_version);
    }
  );


React-Native bridge responses on followed calls:

Api call Response event Description
NativeModules.NielsenEventTrackerBridge.createInstance(appInformation) EVENT_INIT Create NielsenEventTrackerBridge SDK instance
NativeModules.NielsenEventTrackerBridge.userOptOutURLString(sdk_id) EVENT_OPTOUT_URL Get optout url link string
NativeModules.NielsenEventTrackerBridge.getOptOutStatus(sdk_id) EVENT_OPTOUT_STATUS Get optout status value
NativeModules.NielsenEventTrackerBridge.getDemographicId(sdk_id) EVENT_DEMOGRAPHIC_ID Get demographic id string
NativeModules.NielsenEventTrackerBridge.getMeterVersion(sdk_id) EVENT_METER_VERSION Get meter version string

SDK Initialization

The bridge implementations above allow the usage of multiple instances of the Nielsen App SDK. The latest version of the Nielsen App SDK allows instantiating multiple instances of the SDK object, which can be used simultaneously without any issue. For more information on this please read the relevant App SDK Guide.


The following table contains the list of arguments that can be passed via the AppInfo JSON schema.

  • The appid is provided by the Nielsen Technical Account Manager (TAM). The appid is a GUID data type and is specific to the application.
Parameter / Argument Description Source Required? Example
appid Unique id for the application assigned by Nielsen. It is GUID data type. Nielsen-specified Yes PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
intType Used to monitor if the SDK is being used in the ReactNative bridge Client-defined Yes "r"
sfcode Nielsen collection facility to which the SDK should connect.

Italian Clients

  • "it"
Nielsen-specified Yes "it"
nol_devDebug Enables Nielsen console logging. Only required for testing Nielsen-specified While not live "DEBUG"



Sample SDK Initialization Code


NielsenEventTrackerBridge supports multiple SDK instance creation and operations. Hence on successful SDK instance creation NielsenEventTrackerBridge returns the sdk instance id (sdk_id) in asynchronous way to javascript code. This sdk_id will be needed as mandatory parameter to all other functions of NielsenEventTrackerBridge.

Note : Please make sure that you receive and maintain the sdk instance id before calling any function of NielsenEventTrackerBridge.


Below sample javascript code shows how to receive the sdk_id in java script context

    var sdk_id;
    
    //receving sdk instance id from NielsenEventTrackerBridge
    const eventEmitter = new NativeEventEmitter(NativeModules.NielsenEventTrackerBridge);
    var initListner = eventEmitter.addListener(
      "EVENT_INIT",
      (data) => {
        sdk_id = data.id;
        console.log("SDK initialized with id :" + data.id);
      }
    );

    let appInformation = {"appid": "PDA7D5EE6-B1B8-XXXX-XXXX-2A788BCXXXCA","intType": "r"};
    NativeModules.NielsenEventTrackerBridge.createInstance(appInformation);

SDK Instance Removal

The bridge implementations above allow the creation and usage of multiple instances of the Nielsen App SDK. But it's also important to remove the SDK instance once we are done with it. To remove the instance we need to pass sdk instance identifier (which received after instance creation) to method removeInstance() as bshown below

     NativeModules.NielsenEventTrackerBridge.removeInstance(sdk_id);

App Sdk Api Calls

The bridge implementations above provides single api "trackEvent" to process all the playback metadata. Below code snippet demonstrates the same

 let metadata = {
   "owner":"NielsenAppSDKJSHandler",
   "action":"trackEvent",
   "payload":{
      "id":"15861699403999120",
      "data":{
         "event":"",
         "param1":{
            "event":"playhead",
            "type":"content",
            "metadata":{
               "content":{
                  "type":"content",
                  "length":29.2,
                  "assetid":"Seahorse-id"
               }
            },
            "playheadPosition":0
         }
      }
   }
};
 
//call trackEvent api of bridge and pass metadata to be processed
NativeModules.NielsenEventTrackerBridge.trackEvent(sdk_id,metadata);

APP SDK Error & Event Codes

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


Privacy and Opt-Out

Opt-Out Implementation

To opt out, users must have access to "About Nielsen Measurement" page. User can click this page from app settings screen.

Include About Nielsen Measurement and Your Choices link in the Privacy Policy / EULA or as a button near the link to the app's Privacy Policy.

  • URL for the Nielsen Privacy web page should be retrieved from via the userOptOutURLString() method of the SDK bridge and opened in 'WebView' / External browser.
  • If the returned value is null or empty, handle the exception gracefully and retry later.

Due to the limitation that native methods can't return values directly, the URL will be sent to the Javascript context as "EVENT_OPTOUT_URL" event, with the url as the payload.

  var optoutUrlListner = eventEmitter.addListener(
    "EVENT_OPTOUT_URL",
    (data) => {
       console.log("EVENT_OPTOUT_URL :" + data.optouturl);
    }
  );
  NativeModules.NielsenEventTrackerBridge.userOptOutURLString(sdk_id);

The app must provide access to "About Nielsen Measurement" page for the users. Include "About Nielsen Measurement" and Your Choices link in the Privacy Policy / EULA or as a button near the link to the app's Privacy Policy.

Privacy policy iOS.jpg

  • App should provide a UI control like 'close' or 'back' button to close the 'WebView' / External browser.

Users can opt out or opt back into Nielsen Measurement. Opt-Out feature relies on iOS' system setting – "Limit Ad Tracking". The setting can be accessed in the Settings application on any iOS device: Settings → Privacy → Advertising → Limit Ad Tracking.

User is opted out of Nielsen online measurement research when the "Limit Ad Tracking" setting is enabled.

Opt-Out iOS.jpg

Note: For API Version 5.1 and above, App SDK will fire data pings and continue measurement even after the user has opted out from Nielsen measurement on a device. The data ping will be marked as opted-out ping.

Going Live

Following Nielsen testing, users need to make one update to the initialization call to ensure that the site is being measured properly.

  1. Debug Logging: Disable logging by deleting {nol_devDebug: 'DEBUG'} from initialization call.
    • Example Production Initialization Call - Refer to the production initialization call below:

Example:

    let appInformation = {
            "appid": "PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX","intType": "r"
            // Remove Flag:   "nol_devDebug": "DEBUG"
    };
    NativeModules.NielsenEventTrackerBridge.createInstance(appInformation);