Difference between revisions of "DCR React Native Integration"

From Engineering Client Portal

(Going Live)
 
(36 intermediate revisions by 5 users not shown)
Line 1: Line 1:
{{Breadcrumb|}} {{Breadcrumb|Digital}} {{Breadcrumb|International}}  {{CurrentBreadcrumb}}
+
{{Breadcrumb|}} {{Breadcrumb|Digital}} {{Breadcrumb|DCR & DTVR}}  {{CurrentBreadcrumb}}
 
[[Category:Digital]]
 
[[Category:Digital]]
 +
<br/>
 +
<b>Related Topics :</b>
 +
<br/>
 +
[[DCR_React_Native_SimplifiedAPI_Integration|Integrate Nielsen SDK Simplified Api in React-Native App]]
 +
<br/>
 +
[[DCR_React_Native_WebView_Integration|Integrate Nielsen SDK in React-Native Webview App]]
 +
 +
= Integrate Nielsen SDK Legacy Api in React-Native App =
  
 
== Overview ==
 
== 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 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]]), [[Digital Ad Ratings]] (DAR), [[Digital Audio]]. Nielsen SDKs are also equipped to measure static content and can track key life cycle events of an application like:
+
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
 
*Application launch events and how long app was running
 
*Time of viewing a sub section / page in the application.
 
*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 [http://facebook.github.io/react-native/ React-Native] documentation.
 
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 [http://facebook.github.io/react-native/ React-Native] documentation.
 +
<br/>
 +
<p style="color:#C70039;">Note : Support for React-native in Nielsen SDK is available from version 7.2.0.0</p>
  
 
== Prerequisites ==
 
== Prerequisites ==
Line 23: Line 33:
 
This guide covers implementation covers
 
This guide covers implementation covers
  
* the implementation of React-Native bridges for iOS and Android
+
* the implementation of React-Native bridge (NielsenAppApiBridge) for iOS and Android
 
* the usage of the exposed Javascript API
 
* 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 [https://facebook.github.io/react-native/ React-Native] for documentation.
 
What we will not cover is the general setup of React-Native applications. If you are new to React-Native please refer to [https://facebook.github.io/react-native/ 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  ==
 
== Setting up your Environment  ==
 
<div class="section-container auto" data-section>
 
<div class="section-container auto" data-section>
 
   <div class="section">
 
   <div class="section">
     <p class="title" data-section-title>iOS</p>
+
     <big>'''iOS'''</big>
 
     <div class="content" data-section-content>
 
     <div class="content" data-section-content>
  
Line 54: Line 66:
 
   </div>  
 
   </div>  
 
   <div class="section">
 
   <div class="section">
     <p class="title" data-section-title>Android</p>
+
     <big>'''Android'''</big>
 
     <div class="content" data-section-content>
 
     <div class="content" data-section-content>
 
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.
 
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.
 +
 +
<p style="color:#C70039;">Note : Please make sure that you get Android X enabled appsdk.jar from nielsen.</p>
  
 
<code>android/app/libs</code>
 
<code>android/app/libs</code>
Line 64: Line 78:
 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 
<uses-permission android:name="android.permission.INTERNET"/></syntaxhighlight>
 
<uses-permission android:name="android.permission.INTERNET"/></syntaxhighlight>
For more details to handle runtime permissions in Android versions, please visit [https://developer.android.com/training/permissions/requesting.html].  Download the latest ''google-play-services_lib'' and include it in the App’s project in order to use the App SDK.
+
For more details to handle runtime permissions in Android versions, please visit [https://developer.android.com/training/permissions/requesting.html].   
 +
<br/>Nielsen SDK uses google play services library. Hence add the below gradle dependency in your project's build.gradle file
 +
<syntaxhighlight lang="java">
 +
    implementation 'com.google.android.gms:play-services:+'
 +
</syntaxhighlight>
 
* App SDK checks to see if there is a Google service available and updated.
 
* 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.
 
* 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.
Line 85: Line 103:
 
</div>
 
</div>
  
 +
== Creating React-Native bridge (NielsenAppApiBridge) 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
 +
<syntaxhighlight lang="javascript">
 +
import { NativeModules } from 'react-native'
 +
</syntaxhighlight>
 +
 +
 +
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.
  
== Creating React-Native bridges for the Nielsen SDK ==
+
==== iOS ====
<div class="section-container auto" data-section>
+
 
  <div class="section">
+
The iOS implementation of the bridge module consists of two files, a header and an implementation file.
    <p class="title" data-section-title>iOS</p>
+
 
    <div class="content" data-section-content>
+
===== Objective-c =====
<code>NielsenReactBridge.h</code>
+
 
 +
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 <code> NielsenAppApiBridge.h</code>
 
<syntaxhighlight lang="objective-c">
 
<syntaxhighlight lang="objective-c">
// Copyright <YEAR> <COPYRIGHT HOLDER>
+
// 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
 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
Line 108: Line 141:
  
 
#import <React/RCTBridgeModule.h>
 
#import <React/RCTBridgeModule.h>
 +
#import <React/RCTEventEmitter.h>
  
@interface NielsenReactBridge : NSObject <RCTBridgeModule>
+
@interface NielsenAppApiBridge : RCTEventEmitter <RCTBridgeModule>
 
@end
 
@end
 
</syntaxhighlight>
 
</syntaxhighlight>
<code>NielsenReactBridge.m</code>
+
 
 +
 
 +
The actual implementation of the module happens in <code> NielsenAppApiBridge.m</code>
 
<syntaxhighlight lang="objective-c">
 
<syntaxhighlight lang="objective-c">
// Copyright <YEAR> <COPYRIGHT HOLDER>
+
// 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
 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
Line 128: Line 164:
 
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  
#import "NielsenReactBridge.h"
+
#import "NielsenAppApiBridge.h"
 
#import <NielsenAppApi/NielsenAppApi.h>
 
#import <NielsenAppApi/NielsenAppApi.h>
  
static NSString *const TAG = @"NielsenReactBridge";
+
static NSString *const TAG = @"NielsenAppApiBridge";
 +
 
 +
@interface NielsenAppApiBridge() <NielsenAppApiDelegate>
 +
 
 +
@property (nonatomic) NSMutableDictionary<NSString *, NielsenAppApi *> *nlsSDKs;
  
@interface NielsenReactBridge() <NielsenAppApiDelegate>
 
@property (strong) NielsenAppApi* nlsSDk;
 
 
@end
 
@end
  
  
@implementation NielsenReactBridge
+
@implementation NielsenAppApiBridge
 
RCT_EXPORT_MODULE();
 
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
 
- (NSArray<NSString *> *)supportedEvents
 
{
 
{
  return @[@"OptOutUrl"];
+
    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];
 +
    // generate unique id to address created sdk instance
 +
    NSString *sdk_id = [NSString stringWithFormat:@"%lli", (long long)([[NSDate date] timeIntervalSince1970] * 1000)];
 +
 +
    bridgedInfo[@"nol_playerid"] = sdk_id;
 +
    NielsenAppApi *nlsSDK = [[NielsenAppApi 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 play method. The provided channelInfo is
 +
* simply passed on
 
  */
 
  */
void NLSLog(NSString* tag, NSString* format, ...)
+
RCT_EXPORT_METHOD(play:(NSString *)sdk_id :(NSDictionary *)channelInfo)
 
{
 
{
  va_list argList;
+
    NSLog(@"play: %@", channelInfo);
  va_start(argList, format);
+
 
  NSLog(@"%@", [[NSString alloc] initWithFormat:[NSString stringWithFormat:@"[%@]: %@", tag, format] arguments: argList]);
+
    if (self.nlsSDKs[sdk_id]) {
  va_end(argList);
+
        [self.nlsSDKs[sdk_id] play:channelInfo];
 +
    } else {
 +
      NSLog(@"Error: instance %@ not found", sdk_id);
 +
    }
 
}
 
}
  
 
/**
 
/**
 +
* Wrapper for the SDK's loadMetadata method. The provided contentMetaData is
 +
* simply passed on
 
  */
 
  */
RCT_EXPORT_METHOD(init:(NSDictionary *)appInfo)
+
RCT_EXPORT_METHOD(loadMetadata:(NSString *)sdk_id :(NSDictionary *)contentMetaData)
 
{
 
{
  NLSLog(TAG, @"init called with metadat '%@''", appInfo);
+
    NSLog(@"loadMetadata: %@", contentMetaData);
  
  if (!self.nlsSDk) {
+
    if (self.nlsSDKs[sdk_id]) {
    self.nlsSDk= [[NielsenAppApi alloc] initWithAppInfo:appInfo delegate:self];
+
        [self.nlsSDKs[sdk_id] loadMetadata:contentMetaData];
  }
+
    } else {
 +
      NSLog(@"Error: instance %@ not found", sdk_id);
 +
    }
 
}
 
}
  
 
/**
 
/**
 +
* Wrapper for the SDK's stop method.
 
  */
 
  */
RCT_EXPORT_METHOD(play:(NSDictionary *)channelInfo)
+
RCT_EXPORT_METHOD(stop:(NSString *)sdk_id)
 
{
 
{
  NLSLog(TAG, @"play called with metadata '%@'", channelInfo);
+
    NSLog( @"stop");
  
  if (self.nlsSDk) {
+
    if (self.nlsSDKs[sdk_id]) {
    [self.nlsSDk play:channelInfo];
+
        [self.nlsSDKs[sdk_id] stop];
  }
+
    } else {
 +
      NSLog(@"Error: instance %@ not found", sdk_id);
 +
    }
 
}
 
}
  
 
/**
 
/**
 +
* Wrapper for the SDK's end method.
 
  */
 
  */
RCT_EXPORT_METHOD(loadMetadata:(NSDictionary *)contentMetaData)
+
RCT_EXPORT_METHOD(end:(NSString *)sdk_id)
 
{
 
{
  NLSLog(TAG, @"loadMetadata called with '%@'", contentMetaData);
+
    NSLog(@"end");
  
  if (self.nlsSDk) {
+
    if (self.nlsSDKs[sdk_id]) {
    [self.nlsSDk loadMetadata:contentMetaData];
+
        [self.nlsSDKs[sdk_id] end];
  }
+
    } else {
 +
      NSLog(@"Error: instance %@ not found", sdk_id);
 +
    }
 
}
 
}
  
 
/**
 
/**
 +
* Wrapper for the SDK's playheadPosition method. The provided playhead is passed on to the SDK
 
  */
 
  */
RCT_EXPORT_METHOD(setPlayheadPosition:(nonnull NSNumber *)ph)
+
RCT_EXPORT_METHOD(setPlayheadPosition:(NSString *)sdk_id :(nonnull NSNumber *)ph)
 
{
 
{
  NLSLog(TAG, @"setHeadPosition called with '%@'",ph);
+
    NSLog(@"setPlayheadPosition: %@",ph);
  
  if (self.nlsSDk) {
+
    if (self.nlsSDKs[sdk_id]) {
    [self.nlsSDk playheadPosition:[ph longLongValue]];
+
        [self.nlsSDKs[sdk_id] playheadPosition:[ph longLongValue]];
  }
+
    } else {
 +
      NSLog(@"Error: instance %@ not found", sdk_id);
 +
    }
 
}
 
}
  
 
/**
 
/**
 +
* Wrapper for the SDK's sendID3 method. The provided  string is passed on to the SDK
 
  */
 
  */
RCT_EXPORT_METHOD(stop)
+
RCT_EXPORT_METHOD(sendID3:(NSString *)sdk_id :(nonnull NSString *)id3)
 
{
 
{
  NLSLog(TAG, @"stop called");
+
    NSLog(@"sendID3: %@",id3);
 +
 
 +
    if (self.nlsSDKs[sdk_id]) {
 +
        [self.nlsSDKs[sdk_id] sendID3:id3];
 +
    } else {
 +
      NSLog(@"Error: instance %@ not found", sdk_id);
 +
    }
 +
}
  
  if (self.nlsSDk) {
+
/**
     [self.nlsSDk stop];
+
* 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
RCT_EXPORT_METHOD(end)
+
* EVENT_OPTOUT_URL event, so the url can be captured
 +
*/
 +
RCT_EXPORT_METHOD(userOptOutURLString:(NSString *)sdk_id)
 
{
 
{
  NLSLog(TAG, @"end called");
+
    NSLog(@"userOptOutURLString: %@", sdk_id);
  
  if (self.nlsSDk) {
+
    if (self.nlsSDKs[sdk_id]) {
    [self.nlsSDk end];
+
        [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
RCT_EXPORT_METHOD(optOutUrl)
+
* 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 sendEventWithName:@"OptOutUrl" body:@{@"url": self.nlsSDk.optOutURL}];
+
   self.nlsSDKs = nil;
 
}
 
}
 +
 
@end
 
@end
 
</syntaxhighlight>
 
</syntaxhighlight>
    </div>
+
 
  </div>  
+
===== Swift =====
  <div class="section">
+
 
    <p class="title" data-section-title>Android</p>
+
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.
     <div class="content" data-section-content>
+
 
<code>com/nielsen/app/react/NielsenPackage.java</code>
+
The header file is <code> NielsenAppApiBridge.m</code>
 +
<syntaxhighlight lang="objective-c">
 +
// 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(NielsenAppApiBridge, RCTEventEmitter)
 +
 
 +
RCT_EXTERN_METHOD(createInstance:(NSDictionary *)appInfo)
 +
RCT_EXTERN_METHOD(play:(NSString *)sdk_id :(NSDictionary *)channelInfo)
 +
RCT_EXTERN_METHOD(loadMetadata:(NSString *)sdk_id :(NSDictionary *)contentMetaData)
 +
RCT_EXTERN_METHOD(stop:(NSString *)sdk_id)
 +
RCT_EXTERN_METHOD(end:(NSString *)sdk_id)
 +
RCT_EXTERN_METHOD(setPlayheadPosition:(NSString *)sdk_id :(nonnull NSNumber *)ph)
 +
RCT_EXTERN_METHOD(sendID3:(NSString *)sdk_id :(nonnull NSString *)id3)
 +
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
 +
</syntaxhighlight>
 +
 
 +
 
 +
The actual implementation of the module happens in <code> NielsenAppApiBridge.swift</code>
 +
<syntaxhighlight lang="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(NielsenAppApiBridge)
 +
class NielsenAppApiBridge: RCTEventEmitter, NielsenAppApiDelegate {
 +
 
 +
  private let TAG = "NielsenAppApiBridge"
 +
 
 +
  private var nlsSDKs: [String:NielsenAppApi]? = 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
 +
    // generate unique id to address created sdk instance
 +
    let sdk_id = String(format: "%lli", CUnsignedLongLong(Date().timeIntervalSince1970 * 1000))
 +
 
 +
    bridgedInfo["nol_playerid"] = sdk_id
 +
    let nlsSDK = NielsenAppApi(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 play method. The provided channelInfo is
 +
  * simply passed on
 +
  */
 +
  @objc
 +
  func play(_ sdk_id: String, _ channelInfo: Dictionary<String, Any>)
 +
  {
 +
    NSLog("play: \(channelInfo)")
 +
 
 +
     if self.nlsSDKs![sdk_id] != nil {
 +
      self.nlsSDKs![sdk_id]?.play(channelInfo)
 +
    } else {
 +
      NSLog("Error: instance \(sdk_id) not found")
 +
    }
 +
  }
 +
 
 +
  /**
 +
  * Wrapper for the SDK's loadMetadata method. The provided contentMetaData is
 +
  * simply passed on
 +
  */
 +
  @objc
 +
  func loadMetadata(_ sdk_id: String, _ contentMetaData: Dictionary<String, Any>)
 +
  {
 +
    NSLog("loadMetadata: \(contentMetaData)")
 +
 
 +
    if self.nlsSDKs![sdk_id] != nil {
 +
      self.nlsSDKs![sdk_id]?.loadMetadata(contentMetaData)
 +
    } else {
 +
    NSLog("Error: instance \(sdk_id) not found")
 +
    }
 +
  }
 +
 
 +
  /**
 +
  * Wrapper for the SDK's stop method.
 +
  */
 +
  @objc
 +
  func stop(_ sdk_id: String)
 +
  {
 +
    NSLog("stop: \(sdk_id)")
 +
 
 +
    if self.nlsSDKs![sdk_id] != nil {
 +
      self.nlsSDKs![sdk_id]?.stop()
 +
    } else {
 +
      NSLog("Error: instance \(sdk_id) not found")
 +
    }
 +
  }
 +
 
 +
  /**
 +
  * Wrapper for the SDK's end method.
 +
  */
 +
  @objc
 +
  func end(_ sdk_id: String)
 +
  {
 +
    NSLog("end: \(sdk_id)")
 +
 
 +
    if self.nlsSDKs![sdk_id] != nil {
 +
      self.nlsSDKs![sdk_id]?.end()
 +
    } else {
 +
      NSLog("Error: instance \(sdk_id) not found")
 +
    }
 +
  }
 +
 
 +
  /**
 +
  * Wrapper for the SDK's playheadPosition method. The provided playhead is passed on to the SDK
 +
  */
 +
  @objc
 +
  func setPlayheadPosition(_ sdk_id: String, _ ph: NSNumber)
 +
  {
 +
    NSLog("setPlayheadPosition: \(ph)")
 +
 
 +
    if self.nlsSDKs![sdk_id] != nil {
 +
      self.nlsSDKs![sdk_id]?.playheadPosition(ph.int64Value)
 +
    } else {
 +
      NSLog("Error: instance \(sdk_id) not found")
 +
    }
 +
  }
 +
 
 +
  /**
 +
  * Wrapper for the SDK's sendID3 method. The provided  string is passed on to the SDK
 +
  */
 +
  @objc
 +
  func sendID3(_ sdk_id: String, _ id3: String)
 +
  {
 +
    NSLog("sendID3: \(id3)")
 +
 
 +
    if self.nlsSDKs![sdk_id] != nil {
 +
      self.nlsSDKs![sdk_id]?.sendID3(id3)
 +
    } 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
 +
  }
 +
 
 +
}
 +
</syntaxhighlight>
 +
 
 +
==== 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 NielsenAppApiBridge itself. The implementations have been put into the Java package
 +
 
 +
<code>com.nielsen.app.react</code>
 +
 
 +
The package implementation is in <code>com/nielsen/app/react/NielsenPackage.java</code>
 
<syntaxhighlight lang="java">
 
<syntaxhighlight lang="java">
// Copyright <YEAR> <COPYRIGHT HOLDER>
+
// 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
 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
Line 257: Line 701:
 
import com.facebook.react.ReactPackage;
 
import com.facebook.react.ReactPackage;
 
import com.facebook.react.uimanager.ViewManager;
 
import com.facebook.react.uimanager.ViewManager;
import com.nielsen.app.react.NielsenReactBridge;
+
import com.nielsen.app.react.NielsenAppApiBridge;
 
import java.util.ArrayList;
 
import java.util.ArrayList;
 
import java.util.Collections;
 
import java.util.Collections;
Line 267: Line 711:
  
 
     /**
 
     /**
    */
+
    * Override createNativeModules to return our bridge module
 +
    */
 
     @Override
 
     @Override
 
     public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
 
     public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
 
         List<NativeModule> modules = new ArrayList<>();
 
         List<NativeModule> modules = new ArrayList<>();
         modules.add(new NielsenReactBridge(reactContext));
+
         modules.add(new NielsenAppApiBridge(reactContext));
  
 
         return modules;
 
         return modules;
Line 284: Line 729:
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
<code>com/nielsen/app/react/NielsenReactBridge.java</code>
+
 
 +
<code>com/nielsen/app/react/NielsenAppApiBridge.java</code>
 
<syntaxhighlight lang="java">
 
<syntaxhighlight lang="java">
// Copyright <YEAR> <COPYRIGHT HOLDER>
+
// 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
 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
Line 301: Line 747:
  
 
package com.nielsen.app.react;
 
package com.nielsen.app.react;
 
+
import android.content.Context;
 
import android.util.Log;
 
import android.util.Log;
 
import com.facebook.react.bridge.LifecycleEventListener;
 
import com.facebook.react.bridge.LifecycleEventListener;
 
import com.facebook.react.bridge.ReactApplicationContext;
 
import com.facebook.react.bridge.ReactApplicationContext;
 
import com.facebook.react.bridge.ReactContextBaseJavaModule;
 
import com.facebook.react.bridge.ReactContextBaseJavaModule;
 +
import com.facebook.react.modules.core.DeviceEventManagerModule;
 
import com.facebook.react.bridge.ReactMethod;
 
import com.facebook.react.bridge.ReactMethod;
 
import com.facebook.react.bridge.ReadableMap;
 
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.facebook.react.bridge.ReadableMapKeySetIterator;
 
import com.nielsen.app.sdk.AppSdk;
 
import com.nielsen.app.sdk.AppSdk;
Line 314: Line 763:
 
import org.json.JSONObject;
 
import org.json.JSONObject;
 
import org.json.JSONException;
 
import org.json.JSONException;
 +
import java.util.Date;
 +
import java.util.HashMap;
  
 
/**
 
/**
  * NielsenReactBridge is the class briding between react JS code
+
  * NielsenAppApiBridge is the class briding between react JS code
 
  * and the native Nielsen SDK.
 
  * and the native Nielsen SDK.
 
  */
 
  */
public class NielsenReactBridge extends ReactContextBaseJavaModule  
+
public class NielsenAppApiBridge extends ReactContextBaseJavaModule
                                 implements IAppNotifier, LifecycleEventListener {
+
                                 implements IAppNotifier {
  
 
     /**
 
     /**
 
     */
 
     */
     private static final String NIELSEN_TAG = "NielsenReactBridge";
+
    Context mContext;
     private AppSdk mAppSdk = null; // the AppSdk main object
+
     private static final String NIELSEN_TAG = "NielsenAppApiBridge";
 +
    private static final String INSTANCE_PREFIX = "Instance_";
 +
     private HashMap<String, AppSdk> 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 NielsenReactBridge
+
     * Constructor for the NielsenAppApiBridge
 
     * Adds the new instance as LifeCycleEventListener for conttex
 
     * Adds the new instance as LifeCycleEventListener for conttex
 
     * @param context  The react application context
 
     * @param context  The react application context
 
     */
 
     */
     public NielsenReactBridge(ReactApplicationContext context) {
+
     public NielsenAppApiBridge(ReactApplicationContext context) {
 
         super(context);
 
         super(context);
         context.addLifecycleEventListener(this);
+
         mContext = context;
 
     }
 
     }
  
 
     /**
 
     /**
 
     * Implements getName method from ReactContextBaseJavaModule
 
     * Implements getName method from ReactContextBaseJavaModule
     * @return  The constant string 'NielsenReactBridge'
+
     * @return  The constant string 'NielsenAppApiBridge'
 
     */
 
     */
 
     @Override
 
     @Override
 
     public String getName() {
 
     public String getName() {
         return "NielsenReactBridge";
+
         return "NielsenAppApiBridge";
 
     }
 
     }
  
Line 353: Line 823:
  
 
     /**
 
     /**
     * Initializes the module for use  
+
     * Initializes the module for use
     * @param obj   An instance of ReadableMap (mapped JS object) containing
+
     * @param obj An instance of ReadableMap (mapped JS object) containing
     *             initialization meta data
+
     *           initialization meta data
 
     */
 
     */
 
     @ReactMethod
 
     @ReactMethod
     public void init(final ReadableMap obj) {
+
     public void createInstance(final ReadableMap obj) {
 
 
        Log.d(NIELSEN_TAG, "Called init");
 
 
 
        if (null == mAppSdk) {
 
 
             try {
 
             try {
 
                 JSONObject appSdkConfig = readableMapToJSONObject(obj);
 
                 JSONObject appSdkConfig = readableMapToJSONObject(obj);
                 mAppSdk = new AppSdk(getReactApplicationContext(), appSdkConfig, this);
+
                 AppSdk mAppSdk = new AppSdk(getReactApplicationContext(), appSdkConfig, this);
 
                 if (!mAppSdk.isValid())
 
                 if (!mAppSdk.isValid())
 
                 {
 
                 {
                     Log.e(NIELSEN_TAG, "SDK Init failed");
+
                     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) {
 
             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);
 
         }
 
         }
     }
+
     }  
  
 
     /**
 
     /**
Line 381: Line 889:
 
     * @param obj  The ReadableMap instance to be converted
 
     * @param obj  The ReadableMap instance to be converted
 
     * @return      An instance of JSONObject containing the mapped JS object
 
     * @return      An instance of JSONObject containing the mapped JS object
     *              values (if successful, empty otherwise)  
+
     *              values (if successful, empty otherwise)
 
     */
 
     */
 
     static private JSONObject readableMapToJSONObject(final ReadableMap obj) {
 
     static private JSONObject readableMapToJSONObject(final ReadableMap obj) {
  
 
         JSONObject ret = new JSONObject();
 
         JSONObject ret = new JSONObject();
 
 
         try {
 
         try {
 
             ReadableMapKeySetIterator it = obj.keySetIterator();
 
             ReadableMapKeySetIterator it = obj.keySetIterator();
Line 395: Line 902:
 
         }
 
         }
 
         catch (JSONException ex) {
 
         catch (JSONException ex) {
             Log.e(NIELSEN_TAG, ex.getMessage());
+
             Log.e(NIELSEN_TAG, "Exception in readableMapToJSONObject "+ex.getMessage());
 
         }
 
         }
  
 
         return ret;
 
         return ret;
 
     }
 
     }
 +
 +
    /**
 +
    * This function returns NielsenEventTracker instance for id from map
 +
    * @param id An instance id of object
 +
    */
 +
    AppSdk getInstance(String id) {
 +
        AppSdk 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  
+
     * Wrapper for the Nielsen SDK play method. Simply forwards calls
 
     * to the SDK.
 
     * to the SDK.
 
     * @param obj  ReadableMap instance containing the mapped JS meta
 
     * @param obj  ReadableMap instance containing the mapped JS meta
Line 408: Line 939:
 
     */
 
     */
 
     @ReactMethod
 
     @ReactMethod
     public void play(final ReadableMap obj) {
+
     public void play(final String id, final ReadableMap obj) {
 +
        try {
 +
            if (null != id && getInstance(id) != null) {
 +
                JSONObject playObject = readableMapToJSONObject(obj);
 +
                getInstance(id).play(playObject);
 +
            }
 +
        }
 +
        catch (Exception ex) {
 +
            Log.e(NIELSEN_TAG, "Exception in play "+ex.getMessage());
 +
        }
 +
    }
  
        Log.d(NIELSEN_TAG, "Called play " + obj.toString());
+
    /**
         if (null != mAppSdk) {
+
    * Wrapper for the Nielsen SDK loadMetadata method. Simply forwards calls
            JSONObject playObject = readableMapToJSONObject(obj);
+
    * to the SDK.
             mAppSdk.play(playObject);
+
    * @param obj  ReadableMap instance containing the mapped JS meta
 +
    *              data object
 +
    */
 +
    @ReactMethod
 +
    public void loadMetadata(final String id, final ReadableMap obj) {
 +
         try {
 +
            if (null != id && getInstance(id) != null) {
 +
                JSONObject contentMetadata = readableMapToJSONObject(obj);
 +
                getInstance(id).loadMetadata(contentMetadata);
 +
             }
 +
        }
 +
        catch (Exception ex) {
 +
            Log.e(NIELSEN_TAG, "Exception in loadMetadata "+ex.getMessage());
 
         }
 
         }
 
     }
 
     }
  
 
     /**
 
     /**
     * Wrapper for the Nielsen SDK loadMetadata method. Simply forwards calls  
+
     * Wrapper for the Nielsen SDK loadMetadata method. Simply forwards calls
 
     * to the SDK.
 
     * to the SDK.
 
     * @param obj  ReadableMap instance containing the mapped JS meta
 
     * @param obj  ReadableMap instance containing the mapped JS meta
Line 424: Line 977:
 
     */
 
     */
 
     @ReactMethod
 
     @ReactMethod
     public void loadMetadata(final ReadableMap obj) {
+
     public void sendID3(final String id, final String payload) {
 +
        try {
 +
            if (null != id && getInstance(id) != null) {
 +
                getInstance(id).sendID3(payload);
 +
            }
 +
        }
 +
        catch (Exception ex) {
 +
            Log.e(NIELSEN_TAG, "Exception in sendID3 "+ex.getMessage());
 +
        }
 +
    }
  
        Log.d(NIELSEN_TAG,"Called loadMetadata");
+
    /**
         if (null != mAppSdk) {
+
    * Wrapper for the Nielsen SDK loadMetadata method. Simply forwards calls
             JSONObject contentMetadata = readableMapToJSONObject(obj);
+
    * to the SDK.
             mAppSdk.loadMetadata(contentMetadata);
+
    * @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 for the Nielsen SDK setPlayheadPosition method. Simply  
+
     * Wrapper for the Nielsen SDK setPlayheadPosition method. Simply
 
     * forwards calls to the SDK.
 
     * forwards calls to the SDK.
 
     * @param ph    The current playhead position
 
     * @param ph    The current playhead position
 
     */
 
     */
 
     @ReactMethod
 
     @ReactMethod
     public void setPlayheadPosition(final Double ph) {
+
     public void setPlayheadPosition(final String id, final Double ph) {
 
+
        try {
        Log.d(NIELSEN_TAG,"Called setPlayHeadPosition: " + " " + ph);
+
            if (null != id && getInstance(id) != null) {
         if (null != mAppSdk) {
+
                getInstance(id).setPlayheadPosition(ph.longValue());
             mAppSdk.setPlayheadPosition(ph.longValue());
+
            }
 +
        }
 +
         catch (Exception ex) {
 +
             Log.e(NIELSEN_TAG, "Exception in setPlayheadPosition "+ex.getMessage());
 
         }
 
         }
 
     }
 
     }
  
 
     /**
 
     /**
     * Wrapper for the Nielsen SDK stop method. Simply  
+
     * Wrapper for the Nielsen SDK stop method. Simply
 
     * forwards calls to the SDK.
 
     * forwards calls to the SDK.
 
     */
 
     */
 
     @ReactMethod
 
     @ReactMethod
     public void stop() {
+
     public void stop(final String id) {
         Log.d(NIELSEN_TAG, "Called stop");
+
         try {
         if (null != mAppSdk) {
+
            if (null != id && getInstance(id) != null) {
             mAppSdk.stop();
+
                getInstance(id).stop();
 +
            }
 +
         }
 +
        catch (Exception ex) {
 +
             Log.e(NIELSEN_TAG, "Exception in stop "+ex.getMessage());
 
         }
 
         }
 
     }
 
     }
  
 
     /**
 
     /**
     * Wrapper for the Nielsen SDK end method. Simply  
+
     * Wrapper for the Nielsen SDK end method. Simply
 
     * forwards calls to the SDK.
 
     * forwards calls to the SDK.
 
     */
 
     */
 
     @ReactMethod
 
     @ReactMethod
     public void end() {
+
     public void end(String id) {
          
+
         try {
        Log.d(NIELSEN_TAG,"Called end");
+
            if (null != id && getInstance(id) != null) {
         if (null != mAppSdk) {
+
                getInstance(id).end();
             mAppSdk.end();
+
            }
 +
         }
 +
        catch (Exception ex) {
 +
             Log.e(NIELSEN_TAG, "Exception in end "+ex.getMessage());
 
         }
 
         }
 
     }
 
     }
  
 
     /**
 
     /**
     * Wrapper to retrieve the optOutUrl from the Nielsen SDK.  
+
     * Wrapper to retrieve the optOutUrl from the Nielsen SDK.
 
     * Emits a "OptOutUrl" event with the url as payload.
 
     * Emits a "OptOutUrl" event with the url as payload.
 
     * Needs to be catched in JS
 
     * 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
 
     @ReactMethod
     public void optOutUrl() {
+
     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();
 
         WritableMap params = Arguments.createMap();
         if (null != mAppSdk) {
+
         try {
            params.putString("url", mAppSdk.userOptOutURLString());
+
            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());
 
         }
 
         }
 
        getReactApplicationContext()
 
        .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
 
        .emit("OptOutUrl", params);
 
 
     }
 
     }
  
 
     /**
 
     /**
     * Implements LifecycleEventListener's onHostResume method.
+
     * Wrapper to retrieve the optOutUrl from the Nielsen SDK.
     * Uses AppLaunchMeasurementManager.appInForeground to notify SDK about
+
     * Emits a "OptOutUrl" event with the url as payload.
     * app coming to foreground again
+
     * Needs to be catched in JS
 
     */
 
     */
     @Override
+
     @ReactMethod
     public void onHostResume() {
+
     public void getDemographicId(String id) {
 +
        WritableMap params = Arguments.createMap();
 +
        try {
 +
            if (null != id && getInstance(id) != null) {
 +
                params.putString(DEVICE_ID_KEY, getInstance(id).getDemographicId());
 +
                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,AppSdk.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 {
 +
            AppSdk.setDebug(debugState);
 +
        }
 +
        catch (Exception ex) {
 +
            Log.e(NIELSEN_TAG, "Exception in setDebug "+ex.getMessage());
 +
        }
 +
    }
  
        Log.d(NIELSEN_TAG,"Called onHostResume");
+
    @ReactMethod
         if (null != mAppSdk) {
+
    public void suspend(String id) {
             AppLaunchMeasurementManager.appInForeground(getReactApplicationContext());
+
         try {
 +
            if (null != id && getInstance(id) != null) { 
 +
                getInstance(id).suspend();
 +
            }
 +
        }
 +
        catch (Exception ex) {
 +
             Log.e(NIELSEN_TAG, "Exception in suspend "+ex.getMessage());
 
         }
 
         }
 
     }
 
     }
  
     /**
+
     @ReactMethod
    * Implements LifecycleEventListener's onHostPause method.
+
    public void appInBackground(String id) {
    * Uses AppLaunchMeasurementManager.appInBackground to notify SDK about
+
        try {
    * app going to background
+
            if (null != id && getInstance(id) != null) { 
    */
+
                getInstance(id).appInBackground(mContext);
    @Override
+
            }
    public void onHostPause() {
+
        }
 +
        catch (Exception ex) {
 +
            Log.e(NIELSEN_TAG, "Exception in appInBackground "+ex.getMessage());
 +
        }
 +
    }
  
        Log.d(NIELSEN_TAG,"Called onHostPause");
+
    @ReactMethod
         if (null != mAppSdk) {
+
    public void appInForeground(String id) {
             AppLaunchMeasurementManager.appInBackground(getReactApplicationContext());
+
         try {
 +
            if (null != id && getInstance(id) != null) { 
 +
                getInstance(id).appInForeground(mContext);
 +
            }
 +
        }
 +
        catch (Exception ex) {
 +
             Log.e(NIELSEN_TAG, "Exception in appInForeground "+ex.getMessage());
 
         }
 
         }
 
     }
 
     }
  
     /**
+
     @ReactMethod
    * Implements LifecycleEventListener's onHostDestroy method.
+
    public void updateOTT(String id,final ReadableMap obj) {
    */
+
        try {
     @Override
+
            if (null != id && getInstance(id) != null) { 
     public void onHostDestroy() {
+
                JSONObject ottData = readableMapToJSONObject(obj);
         Log.d(NIELSEN_TAG,"Called onHostDestroy");
+
                getInstance(id).updateOTT(ottData);
 +
            }
 +
        }
 +
        catch (Exception ex) {
 +
            Log.e(NIELSEN_TAG, "Exception in updateOTT "+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());
 +
        }
 
     }
 
     }
 
}
 
}
 +
 +
</syntaxhighlight>
 +
<br />
 +
 +
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.
 +
<br />
 +
 +
<syntaxhighlight lang="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.
 +
    }
 
</syntaxhighlight>
 
</syntaxhighlight>
 
</div>
 
</div>
 
</div>
 
</div>
  
<code>NielsenModule.js</code>
+
== 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.
 +
 
 
<syntaxhighlight lang="javascript">
 
<syntaxhighlight lang="javascript">
import { NativeModules } from 'react-native'
+
  const eventEmitter = new NativeEventEmitter(NativeModules.NielsenAppApiBridge);
  
export default NativeModules.NielsenReactBridge
+
  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);
 +
    }
 +
  );
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
<br>
 +
 +
React-Native bridge responses on followed calls:
 +
{| class="wikitable"
 +
|-
 +
! Api call !! Response event !! Description
 +
|-
 +
| NativeModules.NielsenAppApiBridge.createInstance(appInformation) || EVENT_INIT || Create NielsenAppApi SDK instance
 +
|-
 +
| NativeModules.NielsenAppApiBridge.userOptOutURLString(sdk_id) || EVENT_OPTOUT_URL || Get optout url link string
 +
|-
 +
| NativeModules.NielsenAppApiBridge.getOptOutStatus(sdk_id) || EVENT_OPTOUT_STATUS || Get optout status value
 +
|-
 +
| NativeModules.NielsenAppApiBridge.getDemographicId(sdk_id) || EVENT_DEMOGRAPHIC_ID || Get demographic id string
 +
|-
 +
| NativeModules.NielsenAppApiBridge.getMeterVersion(sdk_id) || EVENT_METER_VERSION || Get meter version string
 +
|}
  
 
== SDK Initialization ==
 
== SDK Initialization ==
The bridge implementations above allow the usage of one instance 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 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.
  
  
Line 551: Line 1,319:
 
| appid || Unique id for the application assigned by Nielsen. It is GUID data type.|| Nielsen-specified || Yes || PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
 
| appid || Unique id for the application assigned by Nielsen. It is GUID data type.|| Nielsen-specified || Yes || PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
 
|-
 
|-
| appname || Name of the application || Client-defined || No|| Nielsen Sample App
+
| intType || Used to monitor if the SDK is being used in the ReactNative bridge || Client-defined || Yes||"r"
|-
 
| appversion || Current version of the app used || Client-defined || No || "1.0.2"
 
 
|-
 
|-
 
| sfcode || Nielsen collection facility to which the SDK should connect.
 
| sfcode || Nielsen collection facility to which the SDK should connect.
Line 561: Line 1,327:
 
|-
 
|-
 
| nol_devDebug || Enables Nielsen console logging. Only required for testing
 
| nol_devDebug || Enables Nielsen console logging. Only required for testing
|| Nielsen-specified || Optional || "DEBUG"
+
|| Nielsen-specified || While not live || "DEBUG"
 
|}
 
|}
 
<br />
 
<br />
Line 567: Line 1,333:
  
 
==== Sample SDK Initialization Code ====
 
==== Sample SDK Initialization Code ====
 +
<br/>
 +
NielsenAppApiBridge supports multiple SDK instance creation and operations. Hence on successful SDK instance creation NielsenAppApiBridge 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 NielsenAppApiBridge.<br/>
 +
<p style="color:#C70039;">Note : Please make sure that you receive and maintain the sdk instance id before calling any function of NielsenAppApiBridge.</p><br/>
 +
Below sample javascript code shows how to receive the sdk_id in java script context
 
<syntaxhighlight lang="javascript">
 
<syntaxhighlight lang="javascript">
     import NielsenModule from './NielsenModule';
+
     var sdk_id;
 +
   
 +
    //receving sdk instance id from NielsenAppApiBridge
 +
    const eventEmitter = new NativeEventEmitter(NativeModules.NielsenAppApiBridge);
 +
    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",
+
     let appInformation = {"appid": "PDA7D5EE6-B1B8-XXXX-XXXX-2A788BCXXXCA","intType": "r"};
                          "appversion": "1.0",
+
    NativeModules.NielsenAppApiBridge.createInstance(appInformation);
                          "appname": "app name here",
+
</syntaxhighlight>
                          "sfcode": "it",
+
 
                          "nol_devDebug": @"DEBUG"};
+
== SDK Instance Removal ==
  let nielsenInstance = NielsenModule.init(appInformation);
+
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
 +
 
 +
<syntaxhighlight lang="javascript">
 +
    NativeModules.NielsenAppApiBridge.removeInstance(sdk_id);  
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 581: Line 1,365:
 
To view the Error and Event codes for iOS and Android, please review the [[APP SDK Event Codes|App SDK Event Code]] Reference page.
 
To view the Error and Event codes for iOS and Android, please review the [[APP SDK Event Codes|App SDK Event Code]] Reference page.
  
== Configure Payload ==
+
== Interaction with APP SDK ==
  
=== Configure metadata ===  
+
=== Configure Payload ===
 +
All metadata is passed to the bridges in form of objects containing the in the following described properties. An example metadata object could look like
 +
<syntaxhighlight lang="javascript">
 +
let metadata = {
 +
    'type':'content',
 +
    'assetid':'asset12345',
 +
    'program':'My Program',
 +
    'title':'My Title',
 +
    'length':'42',
 +
    'airdate':'20180302 16:32:00',
 +
    'isfullepisode':'n',
 +
    'adloadtype':'2'
 +
};
 +
</syntaxhighlight>
 +
 
 +
The following section will explain the different values.
 +
 
 +
==== Configure metadata ====  
 
Configure metadata should remain constant throughout the completion of an episode or live stream.
 
Configure metadata should remain constant throughout the completion of an episode or live stream.
 
<br />
 
<br />
Line 595: Line 1,396:
 
<br/>
 
<br/>
  
=== Content metadata ===
+
==== Content metadata ====
 
Content metadata should remain constant throughout the entirety of an episode/clip including when ads play.
 
Content metadata should remain constant throughout the entirety of an episode/clip including when ads play.
  
Line 604: Line 1,405:
 
| type || type of asset || <code>"content"</code> || Yes
 
| type || type of asset || <code>"content"</code> || Yes
 
|-
 
|-
| assetid || unique ID assigned to asset || custom || Yes
+
| assetid || unique ID assigned to asset || custom <br>(no [[Special Characters]]) || Yes
 
|-
 
|-
 
| program ||name of program (25 character limit) || custom || Yes
 
| program ||name of program (25 character limit) || custom || Yes
Line 610: Line 1,411:
 
| title ||name of program (40 character limit) || custom || Yes
 
| title ||name of program (40 character limit) || custom || Yes
 
|-
 
|-
| length || length of content in seconds || <code>seconds</code> (86400 for live stream) || Yes
+
| length || length of content in seconds || <code>seconds</code> (0 for live stream) || Yes
 
|-
 
|-
| airdate || the airdate in the linear TV || YYYYMMDD HH24:MI:SS || Yes
+
| airdate || the airdate in the linear TV; if not known set it to eg. "19700101 00:00:00" || YYYYMMDD HH24:MI:SS || Yes
 
|-
 
|-
 
| isfullepisode || full episode flag || <code>"y"</code>- full episode, <code>"n"</code>- non full episode || Yes
 
| isfullepisode || full episode flag || <code>"y"</code>- full episode, <code>"n"</code>- non full episode || Yes
Line 624: Line 1,425:
 
<br />
 
<br />
  
=== Ad Metadata ===
+
==== Ad Metadata ====
 
The ad metadata (if applicable) should be passed for each individual ad, if ads are available during or before the stream begins.
 
The ad metadata (if applicable) should be passed for each individual ad, if ads are available during or before the stream begins.
 
<br/>
 
<br/>
Line 635: Line 1,436:
 
| assetid || unique ID assigned to ad || custom || ✓
 
| assetid || unique ID assigned to ad || custom || ✓
 
|}
 
|}
 +
<br />
 +
 +
==== Static Measurement ====
 +
The Nielsen SDK is able to monitor Application launch events and how long your app has been running. Once the Nielsen module has been Initialized, pass a metadata object to loadMeta data that follows these rules:
  
== Configure API Calls ==
+
{| class="wikitable"
=== Sample API Sequence ===
+
|-
 +
! Key !! Description !! Data Type !! Value !! Required?
 +
|-
 +
| type || asset type || fixed || <code>'static'</code> || Yes
 +
|-
 +
| assetid || Unique ID for each article || dynamic || custom || Yes
 +
|-
 +
| section || section of each site (e.g. section value should be first level in page URL: website.com/section). Limit to 25 unique values || dynamic || custom || Yes
 +
|}
 +
You only need to do this once upon app start.
 +
 
 +
=== Configure API Calls ===
 +
==== Sample API Sequence ====
 
A Sample API sequence could follow this flow:
 
A Sample API sequence could follow this flow:
 
{| class="wikitable"
 
{| class="wikitable"
Line 643: Line 1,460:
 
! Type !! Sample code !! Description
 
! Type !! Sample code !! Description
 
|-
 
|-
|On App Start||<code>NielsenModule.loadMetadata(contentMetadata);</code> || // contentMetadata Object contains the JSON metadata for the impression
+
|On App Start||<code> NativeModules.NielsenAppApiBridge.loadMetadata(sdk_id,contentMetadata);</code> || // sdk_id - sdk instance id received after creating instance. <br/>contentMetadata - Object contains the JSON metadata for the impression.
 
|-
 
|-
| rowspan="2" | Start of stream || <code>NielsenModule.play(channelName);</code> || // channelName contains JSON metadata of channel/video name being played
+
| rowspan="2" | Start of stream || <code>NativeModules.NielsenAppApiBridge.play(sdk_id, metadata);</code> || // sdk_id - sdk instance id received after creating instance. <br/>metadata contains JSON metadata of channel/video name being played
 
|-
 
|-
| <code>NielsenModule.loadMetadata(contentMetadataObject);</code> || // contentMetadataObject contains the JSON metadata for the content being played
+
| <code> NativeModules.NielsenAppApiBridge.loadMetadata(sdk_id,contentMetadataObject);</code> || // sdk_id - sdk instance id received after creating instance. <br/>contentMetadataObject contains the JSON metadata for the content being played
 
|-
 
|-
| Content || <code>NielsenModule.playheadPosition(position);</code> || // playheadPosition is position of the playhead while the content is being played
+
| Content || <code>NativeModules.NielsenAppApiBridge.setPlayheadPosition(sdk_id,playhead);</code> || // sdk_id - sdk instance id received after creating instance.<br/>playheadPosition is position of the playhead while the content is being played
 
|-
 
|-
| End of Stream || <code>NielsenModule.end();</code> || // Content playback is completed.
+
| End of Stream || <code>NativeModules.NielsenAppApiBridge.end(sdk_id);</code> || // Content playback is completed.
 
|}
 
|}
=== Life cycle of SDK instance ===
+
==== Life cycle of SDK instance ====
 
Life cycle of SDK instance includes four general states:
 
Life cycle of SDK instance includes four general states:
 
# '''Initial state''' – The SDK is not initialized and hence, not ready to process playing information. Once the SDK is moved out of this state, it needs instantiation of the new SDK instance in order to get the instance in the '''Initial state'''.
 
# '''Initial state''' – The SDK is not initialized and hence, not ready to process playing information. Once the SDK is moved out of this state, it needs instantiation of the new SDK instance in order to get the instance in the '''Initial state'''.
Line 661: Line 1,478:
 
## [[DCR_Video_APP_SDK#stop|stop]] – Call this API when the playback is paused, switches between content and ad (within the same content playback) or encounters interruptions.
 
## [[DCR_Video_APP_SDK#stop|stop]] – Call this API when the playback is paused, switches between content and ad (within the same content playback) or encounters interruptions.
 
## [[DCR_Video_APP_SDK#end|end]] – SDK instance exits from Processing state when this API is called.
 
## [[DCR_Video_APP_SDK#end|end]] – SDK instance exits from Processing state when this API is called.
# '''Disabled state''' – The SDK instance is disabled and is not processing playing information. SDK instance moves into this state in one of the following scenarios.
 
## Initialization fails
 
## <code>appDisableApi</code> is called
 
<syntaxhighlight lang="objective-c">
 
@property (assign) BOOL appDisableApi;
 
</syntaxhighlight>
 
  
 
<blockquote>'''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.
 
<blockquote>'''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.
Line 673: Line 1,484:
 
* As soon as the playback resumes, call [[DCR_Video_APP_SDK#loadMetadata|loadMetadata]] and  [[DCR_Video_APP_SDK#playheadPosition|playheadPosition]].</blockquote>
 
* As soon as the playback resumes, call [[DCR_Video_APP_SDK#loadMetadata|loadMetadata]] and  [[DCR_Video_APP_SDK#playheadPosition|playheadPosition]].</blockquote>
  
=== Sequence of Calls ===
+
==== Sequence of Calls ====
=== play ===
+
==== play ====
Use [[DCR_Video_APP_SDK#play|play]] to pass the channel descriptor information through channelName parameter when the user taps the '''Play''' button on the player.
+
Use the play function to pass the channel descriptor information through channelName parameter when the user taps the '''Play''' button on the player.
<syntaxhighlight lang="javascript">   NielsenModule.play(channelInfo);</syntaxhighlight>
+
<syntaxhighlight lang="javascript"> NativeModules.NielsenAppApiBridge.play(sdk_id, channelInfo);</syntaxhighlight>
  
  
=== loadMetadata ===
+
==== loadMetadata ====
<syntaxhighlight lang="javascript">   NielsenModule.loadMetadata(contentMetadata);</syntaxhighlight>
+
The loadMetadata function is used to inform the SDK about new content. The contentMetadata object passed in should contain the values as described above.
 +
<syntaxhighlight lang="javascript">   NativeModules.NielsenAppApiBridge.loadMetadata(sdk_id, contentMetadata);</syntaxhighlight>
  
  
=== playheadPosition ===
+
==== playheadPosition ====
<syntaxhighlight lang="javascript">  NielsenModule.playheadPosition(playheadPos);</syntaxhighlight>
+
Use playheadPosition to tell the SDK about the current position in the video. For live content this should be the Unix timestamp (seconds since Jan-1-1970 UTC). For on-demand content, simply the playhead position in seconds.
 +
<syntaxhighlight lang="javascript">  NativeModules.NielsenAppApiBridge.setPlayheadPosition(sdk_id, playheadPos);</syntaxhighlight>
  
  
=== stop ===
+
==== stop ====
<syntaxhighlight lang="javascript">   NielsenModule.stop();</syntaxhighlight>
+
Tell the SDK that content playback has stopped.
 +
<syntaxhighlight lang="javascript"> NativeModules.NielsenAppApiBridge.stop(sdk_id); </syntaxhighlight>
  
  
=== end ===
+
==== end ====
 
When content stop is initiated and content cannot be resumed from the same position (it can only be restarted from the beginning of stream).
 
When content stop is initiated and content cannot be resumed from the same position (it can only be restarted from the beginning of stream).
<syntaxhighlight lang="javascript">  NielsenModule.end();</syntaxhighlight>
+
<syntaxhighlight lang="javascript">  NativeModules.NielsenAppApiBridge.end(sdk_id); </syntaxhighlight>
  
== Privacy and Opt-Out ==
+
=== Privacy and Opt-Out ===
  
=== Opt-Out Implementation ===
+
==== Opt-Out Implementation ====
 
To opt out, users must have access to "[https://priv-policy.imrworldwide.com/priv/mobile/it/it/optout.html About Nielsen Measurement]" page. User can click this page from app settings screen.
 
To opt out, users must have access to "[https://priv-policy.imrworldwide.com/priv/mobile/it/it/optout.html 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.
 
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 <code>optOutURL()</code> method of the SDK bridge and opened in 'WebView' / External browser.
+
*URL for the Nielsen Privacy web page should be retrieved from via the <code>userOptOutURLString()</code> 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.
 
*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 "OptOutUrl" event, with the url as the payload.
+
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.
  
 
<syntaxhighlight lang="javascript">
 
<syntaxhighlight lang="javascript">
    const nielsen = new NativeEventEmitter(NielsenModule);
+
  var optoutUrlListner = eventEmitter.addListener(
   
+
    "EVENT_OPTOUT_URL",
    const subscription = nielsen.addListener(
+
    (data) => {
      'OptOutUrl',
+
      console.log("EVENT_OPTOUT_URL :" + data.optouturl);
      (data) => {  
+
     }
        //display data.url
+
  );
      }
+
  NativeModules.NielsenAppApiBridge.userOptOutURLString(sdk_id);  
    );
 
     NielsenModule.optOutUrl();
 
  //...
 
  subscription.remove(); // do not forget to unsubscribe
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 733: Line 1,543:
  
 
<blockquote>'''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.</blockquote>
 
<blockquote>'''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.</blockquote>
 
  
 
== Going Live ==
 
== Going Live ==
Line 745: Line 1,554:
 
<syntaxhighlight lang="javascript">
 
<syntaxhighlight lang="javascript">
 
     let appInformation = {
 
     let appInformation = {
             "appid": "PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
+
             "appid": "PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX","intType": "r"
            "sfcode": "it"
 
 
             // Remove Flag:  "nol_devDebug": "DEBUG"
 
             // Remove Flag:  "nol_devDebug": "DEBUG"
 
     };
 
     };
     NielsenModule.initi(appInformation);
+
     NativeModules.NielsenAppApiBridge.createInstance(appInformation);
 
</syntaxhighlight>
 
</syntaxhighlight>

Latest revision as of 22:06, 26 June 2020

Engineering Portal breadcrumbArrow.png Digital breadcrumbArrow.png DCR & DTVR breadcrumbArrow.png DCR React Native Integration

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

Integrate Nielsen SDK Legacy 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 (NielsenAppApiBridge) 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 (NielsenAppApiBridge) 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 NielsenAppApiBridge.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 NielsenAppApiBridge : RCTEventEmitter <RCTBridgeModule>
@end


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

static NSString *const TAG = @"NielsenAppApiBridge";

@interface NielsenAppApiBridge() <NielsenAppApiDelegate>

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

@end


@implementation NielsenAppApiBridge
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];
    // generate unique id to address created sdk instance
    NSString *sdk_id = [NSString stringWithFormat:@"%lli", (long long)([[NSDate date] timeIntervalSince1970] * 1000)];

    bridgedInfo[@"nol_playerid"] = sdk_id;
    NielsenAppApi *nlsSDK = [[NielsenAppApi 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 play method. The provided channelInfo is
 * simply passed on
 */
RCT_EXPORT_METHOD(play:(NSString *)sdk_id :(NSDictionary *)channelInfo)
{
    NSLog(@"play: %@", channelInfo);

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

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

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

/**
 * Wrapper for the SDK's stop method.
 */
RCT_EXPORT_METHOD(stop:(NSString *)sdk_id)
{
    NSLog( @"stop");

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

/**
 * Wrapper for the SDK's end method.
 */
RCT_EXPORT_METHOD(end:(NSString *)sdk_id)
{
    NSLog(@"end");

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

/**
 * Wrapper for the SDK's playheadPosition method. The provided playhead is passed on to the SDK
 */
RCT_EXPORT_METHOD(setPlayheadPosition:(NSString *)sdk_id :(nonnull NSNumber *)ph)
{
    NSLog(@"setPlayheadPosition: %@",ph);

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

/**
 * Wrapper for the SDK's sendID3 method. The provided  string is passed on to the SDK
 */
RCT_EXPORT_METHOD(sendID3:(NSString *)sdk_id :(nonnull NSString *)id3)
{
    NSLog(@"sendID3: %@",id3);

    if (self.nlsSDKs[sdk_id]) {
        [self.nlsSDKs[sdk_id] sendID3:id3];
    } 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 NielsenAppApiBridge.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(NielsenAppApiBridge, RCTEventEmitter)

RCT_EXTERN_METHOD(createInstance:(NSDictionary *)appInfo)
RCT_EXTERN_METHOD(play:(NSString *)sdk_id :(NSDictionary *)channelInfo)
RCT_EXTERN_METHOD(loadMetadata:(NSString *)sdk_id :(NSDictionary *)contentMetaData)
RCT_EXTERN_METHOD(stop:(NSString *)sdk_id)
RCT_EXTERN_METHOD(end:(NSString *)sdk_id)
RCT_EXTERN_METHOD(setPlayheadPosition:(NSString *)sdk_id :(nonnull NSNumber *)ph)
RCT_EXTERN_METHOD(sendID3:(NSString *)sdk_id :(nonnull NSString *)id3)
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 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(NielsenAppApiBridge)
class NielsenAppApiBridge: RCTEventEmitter, NielsenAppApiDelegate {

  private let TAG = "NielsenAppApiBridge"

  private var nlsSDKs: [String:NielsenAppApi]? = 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
    // generate unique id to address created sdk instance
    let sdk_id = String(format: "%lli", CUnsignedLongLong(Date().timeIntervalSince1970 * 1000))

    bridgedInfo["nol_playerid"] = sdk_id
    let nlsSDK = NielsenAppApi(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 play method. The provided channelInfo is
  * simply passed on
  */
  @objc
  func play(_ sdk_id: String, _ channelInfo: Dictionary<String, Any>)
  {
    NSLog("play: \(channelInfo)")

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

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

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

  /**
  * Wrapper for the SDK's stop method.
  */
  @objc
  func stop(_ sdk_id: String)
  {
    NSLog("stop: \(sdk_id)")

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

  /**
  * Wrapper for the SDK's end method.
  */
  @objc
  func end(_ sdk_id: String)
  {
    NSLog("end: \(sdk_id)")

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

  /**
  * Wrapper for the SDK's playheadPosition method. The provided playhead is passed on to the SDK
  */
  @objc
  func setPlayheadPosition(_ sdk_id: String, _ ph: NSNumber)
  {
    NSLog("setPlayheadPosition: \(ph)")

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

  /**
  * Wrapper for the SDK's sendID3 method. The provided  string is passed on to the SDK
  */
  @objc
  func sendID3(_ sdk_id: String, _ id3: String)
  {
    NSLog("sendID3: \(id3)")

    if self.nlsSDKs![sdk_id] != nil {
      self.nlsSDKs![sdk_id]?.sendID3(id3)
    } 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 NielsenAppApiBridge 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.NielsenAppApiBridge;
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 NielsenAppApiBridge(reactContext));

        return modules;
    }

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

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

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

    /**
    */
    Context mContext;
    private static final String NIELSEN_TAG = "NielsenAppApiBridge";
    private static final String INSTANCE_PREFIX = "Instance_";
    private HashMap<String, AppSdk> 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 NielsenAppApiBridge
     * Adds the new instance as LifeCycleEventListener for conttex
     * @param context  The react application context
     */
    public NielsenAppApiBridge(ReactApplicationContext context) {
        super(context);
        mContext = context;
    }

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

    /**
     * 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 = readableMapToJSONObject(obj);
                AppSdk mAppSdk = new AppSdk(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 readableMapToJSONObject(final ReadableMap obj) {

        JSONObject ret = new JSONObject();
        try {
            ReadableMapKeySetIterator it = obj.keySetIterator();
            while (it.hasNextKey()) {
                String key = it.nextKey();
                ret.put(key, obj.getDynamic(key).asString());
            }
        }
        catch (JSONException ex) {
            Log.e(NIELSEN_TAG, "Exception in readableMapToJSONObject "+ex.getMessage());
        }

        return ret;
    }

     /**
     * This function returns NielsenEventTracker instance for id from map
     * @param id An instance id of object
     */
    AppSdk getInstance(String id) {
        AppSdk 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 play(final String id, final ReadableMap obj) {
        try {
            if (null != id && getInstance(id) != null) {
                JSONObject playObject = readableMapToJSONObject(obj);
                getInstance(id).play(playObject);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in play "+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 loadMetadata(final String id, final ReadableMap obj) {
        try {
            if (null != id && getInstance(id) != null) {
                JSONObject contentMetadata = readableMapToJSONObject(obj);
                getInstance(id).loadMetadata(contentMetadata);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in loadMetadata "+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 sendID3(final String id, final String payload) {
        try {
            if (null != id && getInstance(id) != null) {
                getInstance(id).sendID3(payload);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in sendID3 "+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 for the Nielsen SDK setPlayheadPosition method. Simply
     * forwards calls to the SDK.
     * @param ph    The current playhead position
     */
    @ReactMethod
    public void setPlayheadPosition(final String id, final Double ph) {
        try {
            if (null != id && getInstance(id) != null) {
                getInstance(id).setPlayheadPosition(ph.longValue());
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in setPlayheadPosition "+ex.getMessage());
        }
    }

    /**
     * Wrapper for the Nielsen SDK stop method. Simply
     * forwards calls to the SDK.
     */
    @ReactMethod
    public void stop(final String id) {
        try {
            if (null != id && getInstance(id) != null) {
                getInstance(id).stop();
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in stop "+ex.getMessage());
        }
    }

    /**
     * Wrapper for the Nielsen SDK end method. Simply
     * forwards calls to the SDK.
     */
    @ReactMethod
    public void end(String id) {
        try {
            if (null != id && getInstance(id) != null) {
                getInstance(id).end();
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in end "+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) {
                params.putString(DEVICE_ID_KEY, getInstance(id).getDemographicId());
                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,AppSdk.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 {
            AppSdk.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 updateOTT(String id,final ReadableMap obj) {
        try {
            if (null != id && getInstance(id) != null) {  
                JSONObject ottData = readableMapToJSONObject(obj);
                getInstance(id).updateOTT(ottData);
            }
        }
        catch (Exception ex) {
            Log.e(NIELSEN_TAG, "Exception in updateOTT "+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.
    }

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.NielsenAppApiBridge);

  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.NielsenAppApiBridge.createInstance(appInformation) EVENT_INIT Create NielsenAppApi SDK instance
NativeModules.NielsenAppApiBridge.userOptOutURLString(sdk_id) EVENT_OPTOUT_URL Get optout url link string
NativeModules.NielsenAppApiBridge.getOptOutStatus(sdk_id) EVENT_OPTOUT_STATUS Get optout status value
NativeModules.NielsenAppApiBridge.getDemographicId(sdk_id) EVENT_DEMOGRAPHIC_ID Get demographic id string
NativeModules.NielsenAppApiBridge.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


NielsenAppApiBridge supports multiple SDK instance creation and operations. Hence on successful SDK instance creation NielsenAppApiBridge 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 NielsenAppApiBridge.

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


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

    var sdk_id;
    
    //receving sdk instance id from NielsenAppApiBridge
    const eventEmitter = new NativeEventEmitter(NativeModules.NielsenAppApiBridge);
    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.NielsenAppApiBridge.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.NielsenAppApiBridge.removeInstance(sdk_id);

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.

Interaction with APP SDK

Configure Payload

All metadata is passed to the bridges in form of objects containing the in the following described properties. An example metadata object could look like

let metadata = {
    'type':'content',
    'assetid':'asset12345',
    'program':'My Program',
    'title':'My Title',
    'length':'42',
    'airdate':'20180302 16:32:00',
    'isfullepisode':'n',
    'adloadtype':'2'
};

The following section will explain the different values.

Configure metadata

Configure metadata should remain constant throughout the completion of an episode or live stream.

Key Description Values Required
channelName Any string representing the channel/stream custom


Content metadata

Content metadata should remain constant throughout the entirety of an episode/clip including when ads play.

Keys Description Values Required
type type of asset "content" Yes
assetid unique ID assigned to asset custom
(no Special Characters)
Yes
program name of program (25 character limit) custom Yes
title name of program (40 character limit) custom Yes
length length of content in seconds seconds (0 for live stream) Yes
airdate the airdate in the linear TV; if not known set it to eg. "19700101 00:00:00" YYYYMMDD HH24:MI:SS Yes
isfullepisode full episode flag "y"- full episode, "n"- non full episode Yes
adloadtype type of ad load:

"1" Linear – matches TV ad load

"2" Dynamic – Dynamic Ad Insertion (DAI)

"2" - DCR measures content with dynamic ads Yes


Ad Metadata

The ad metadata (if applicable) should be passed for each individual ad, if ads are available during or before the stream begins.

Keys Description Values Required
type type of ad 'preroll', 'midroll', or 'postroll'
assetid unique ID assigned to ad custom


Static Measurement

The Nielsen SDK is able to monitor Application launch events and how long your app has been running. Once the Nielsen module has been Initialized, pass a metadata object to loadMeta data that follows these rules:

Key Description Data Type Value Required?
type asset type fixed 'static' Yes
assetid Unique ID for each article dynamic custom Yes
section section of each site (e.g. section value should be first level in page URL: website.com/section). Limit to 25 unique values dynamic custom Yes

You only need to do this once upon app start.

Configure API Calls

Sample API Sequence

A Sample API sequence could follow this flow:

Type Sample code Description
On App Start NativeModules.NielsenAppApiBridge.loadMetadata(sdk_id,contentMetadata); // sdk_id - sdk instance id received after creating instance.
contentMetadata - Object contains the JSON metadata for the impression.
Start of stream NativeModules.NielsenAppApiBridge.play(sdk_id, metadata); // sdk_id - sdk instance id received after creating instance.
metadata contains JSON metadata of channel/video name being played
NativeModules.NielsenAppApiBridge.loadMetadata(sdk_id,contentMetadataObject); // sdk_id - sdk instance id received after creating instance.
contentMetadataObject contains the JSON metadata for the content being played
Content NativeModules.NielsenAppApiBridge.setPlayheadPosition(sdk_id,playhead); // sdk_id - sdk instance id received after creating instance.
playheadPosition is position of the playhead while the content is being played
End of Stream NativeModules.NielsenAppApiBridge.end(sdk_id); // Content playback is completed.

Life cycle of SDK instance

Life cycle of SDK instance includes four general states:

  1. Initial state – The SDK is not initialized and hence, not ready to process playing information. Once the SDK is moved out of this state, it needs instantiation of the new SDK instance in order to get the instance in the Initial state.
  2. Idle state – The SDK is initialized and is ready to process playing information. Once Initialized, the SDK instance is not processing any data, but is listening for the play event to occur.
  3. Processing state – The SDK instance is processing playing information. play and loadMetadata calls move the SDK instance into this state. In this state, the SDK instance will be able to process the following calls.
    1. playheadPosition – Call this API every one second when playhead position timer is fired.
    2. stop – Call this API when the playback is paused, switches between content and ad (within the same content playback) or encounters interruptions.
    3. end – SDK instance exits from Processing state when this API is called.

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.

Note: In case of any interruptions during playback due to alarm, calendar, call, flight mode, Wi-Fi toggle, channel change, etc., call stop to stop the measurement.

Sequence of Calls

play

Use the play function to pass the channel descriptor information through channelName parameter when the user taps the Play button on the player.

  NativeModules.NielsenAppApiBridge.play(sdk_id, channelInfo);


loadMetadata

The loadMetadata function is used to inform the SDK about new content. The contentMetadata object passed in should contain the values as described above.

    NativeModules.NielsenAppApiBridge.loadMetadata(sdk_id, contentMetadata);


playheadPosition

Use playheadPosition to tell the SDK about the current position in the video. For live content this should be the Unix timestamp (seconds since Jan-1-1970 UTC). For on-demand content, simply the playhead position in seconds.

   NativeModules.NielsenAppApiBridge.setPlayheadPosition(sdk_id, playheadPos);


stop

Tell the SDK that content playback has stopped.

 NativeModules.NielsenAppApiBridge.stop(sdk_id);


end

When content stop is initiated and content cannot be resumed from the same position (it can only be restarted from the beginning of stream).

   NativeModules.NielsenAppApiBridge.end(sdk_id);

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.NielsenAppApiBridge.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.NielsenAppApiBridge.createInstance(appInformation);