DCR React Native Integration: Difference between revisions

From Engineering Client Portal

No edit summary
 
(47 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 17: Line 27:
If you do not have any of these prerequisites or if you have any questions, please contact our SDK sales support team.
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.
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 ==
==  Implementation ==
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.
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>
The first step is to ensure that the following frameworks and libraries are imported into the Frameworks folder of the Xcode project before creating an instance of the Nielsen App SDK object.


Nielsen App SDK is compatible with Apple iOS versions 9.0 and above.
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
* UIKit.framework
Line 44: Line 59:
* CoreMedia.framework
* CoreMedia.framework
* NielsenAppApi.framework
* NielsenAppApi.framework
* libc++.tbd (as SDK contains Objective C++ source file)
** Alternatively, include -lstdc++ in Build Settings → Other Linker Flag of the Xcode project


<blockquote>'''Example'''
Nielsens App SDK is compatible with Apple iOS versions 9.0 and above.
* Extract “NielsenAppApi.Framework” from the Nielsen App SDK sample app and copy it to Frameworks folder of the Xcode project.
 
* Add the code <code>-#import NielsenAppApi/NielsenAppApi.h</code> to the View Controller’s header file.</blockquote>
Ensure that the following are included in the Linked Frameworks and Libraries list (located in the project’s Summary settings).
* Nielsen App SDK
* iOS security framework
<br />
<br />
     </div>
     </div>
   </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 Java AppSdk.jar library that runs on the Android’s Dalvik Virtual Machine.
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>


Add the following permissions on the project’s ''AndroidManifest.xml'' file.
The next step is to add the following permissions on the project’s ''AndroidManifest.xml'' file.
<syntaxhighlight lang="java"><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:required="false" />
<syntaxhighlight lang="java"><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.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 87: 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.
==== iOS ====
The iOS implementation of the bridge module consists of two files, a header and an implementation file.
===== Objective-c =====


== Creating React-Native bridges for the Nielsen SDK ==
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.
<div class="section-container auto" data-section>
 
  <div class="section">
The header file is <code> NielsenAppApiBridge.h</code>
    <p class="title" data-section-title>iOS</p>
    <div class="content" data-section-content>
<code>NielsenReactBridge.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 110: 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 130: 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
  */
  */
void NLSLog(NSString* tag, NSString* format, ...)
- (NSArray<NSString *> *)supportedEvents
{
{
  va_list argList;
    return @[@"EVENT_INIT", @"EVENT_OPTOUT_URL", @"EVENT_OPTOUT_STATUS", @"EVENT_DEMOGRAPHIC_ID", @"EVENT_METER_VERSION"];
  va_start(argList, format);
  NSLog(@"%@", [[NSString alloc] initWithFormat:[NSString stringWithFormat:@"[%@]: %@", tag, format] arguments: argList]);
  va_end(argList);
}
}


/**
/**
* 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(init:(NSDictionary *)appInfo)
RCT_EXPORT_METHOD(play:(NSString *)sdk_id :(NSDictionary *)channelInfo)
{
{
  NLSLog(TAG, @"init called with metadat '%@''", appInfo);
    NSLog(@"play: %@", channelInfo);


  if (!self.nlsSDk) {
    if (self.nlsSDKs[sdk_id]) {
    self.nlsSDk= [[NielsenAppApi alloc] initWithAppInfo:appInfo delegate:self];
        [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(play:(NSDictionary *)channelInfo)
RCT_EXPORT_METHOD(loadMetadata:(NSString *)sdk_id :(NSDictionary *)contentMetaData)
{
{
  NLSLog(TAG, @"play called with metadata '%@'", channelInfo);
    NSLog(@"loadMetadata: %@", contentMetaData);


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


/**
/**
* Wrapper for the SDK's stop method.
  */
  */
RCT_EXPORT_METHOD(loadMetadata:(NSDictionary *)contentMetaData)
RCT_EXPORT_METHOD(stop:(NSString *)sdk_id)
{
{
  NLSLog(TAG, @"loadMetadata called with '%@'", contentMetaData);
    NSLog( @"stop");


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


/**
/**
* Wrapper for the SDK's end method.
  */
  */
RCT_EXPORT_METHOD(setPlayheadPosition:(nonnull NSNumber *)ph)
RCT_EXPORT_METHOD(end:(NSString *)sdk_id)
{
{
  NLSLog(TAG, @"setHeadPosition called with '%@'",ph);
    NSLog(@"end");


  if (self.nlsSDk) {
    if (self.nlsSDKs[sdk_id]) {
    [self.nlsSDk playheadPosition:[ph longLongValue]];
        [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(stop)
RCT_EXPORT_METHOD(setPlayheadPosition:(NSString *)sdk_id :(nonnull NSNumber *)ph)
{
{
  NLSLog(TAG, @"stop called");
    NSLog(@"setPlayheadPosition: %@",ph);


  if (self.nlsSDk) {
    if (self.nlsSDKs[sdk_id]) {
    [self.nlsSDk stop];
        [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(end)
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)
{
{
   NLSLog(TAG, @"end called");
    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
</syntaxhighlight>
 
===== 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 <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.nlsSDk) {
    if self.nlsSDKs![sdk_id] != nil {
    [self.nlsSDk end];
      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
  }
}
}
@end
</syntaxhighlight>
</syntaxhighlight>
    </div>
 
  </div>
==== Android ====
  <div class="section">
 
    <p class="title" data-section-title>Android</p>
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
    <div class="content" data-section-content>
 
<code>com/nielsen/app/react/NielsenPackage.java</code>
<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 247: 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 257: 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 274: 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 291: 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 304: 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 343: 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 371: 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 385: 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 398: 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 414: 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());
         }
         }
     }
     }


     /**
     /**
     * 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 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());
        }
    }


         Log.d(NIELSEN_TAG,"Called onHostResume");
    /**
         if (null != mAppSdk) {
    * Wrapper to retrieve the optOutUrl from the Nielsen SDK.
             AppLaunchMeasurementManager.appInForeground(getReactApplicationContext());
    * 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());
         }
         }
     }
     }


     /**
     /**
     * Implements LifecycleEventListener's onHostPause method.
     * Wrapper to retrieve the optOutUrl from the Nielsen SDK.
     * Uses AppLaunchMeasurementManager.appInBackground to notify SDK about
     * Emits a "OptOutUrl" event with the url as payload.
     * app going to background
     * Needs to be catched in JS
     */
     */
     @Override
     @ReactMethod
     public void onHostPause() {
     public void getNielsenId(String id) {
 
         WritableMap params = Arguments.createMap();
         Log.d(NIELSEN_TAG,"Called onHostPause");
         try {
         if (null != mAppSdk) {
            if (null != id && getInstance(id) != null) {
             AppLaunchMeasurementManager.appInBackground(getReactApplicationContext());
                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());
         }
         }
     }
     }


     /**
     /**
     * Implements LifecycleEventListener's onHostDestroy method.
     * Wrapper to retrieve the optOutUrl from the Nielsen SDK.
    * Emits a "OptOutUrl" event with the url as payload.
    * Needs to be catched in JS
     */
     */
     @Override
     @ReactMethod
     public void onHostDestroy() {
     public void getDemographicId(String id) {
         Log.d(NIELSEN_TAG,"Called onHostDestroy");
         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());
        }
     }
     }
}
}
</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>


== 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">
  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);
    }
  );
</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 516: 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 526: 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 532: 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">
    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);
</syntaxhighlight>
== 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


<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
    let appInformation = {"appid": "PDA7D5EE6-B1B8-XXXX-XXXX-2A788BCXXXCA",
    NativeModules.NielsenAppApiBridge.removeInstance(sdk_id);  
                                      "appversion": "1.0",
                                      "appname": "app name here",
                                      "sfcode": "it",
                                      "nol_devDebug": @"DEBUG"};
    [[NielsenAppApi alloc] initWithAppInfo:appInformation delegate:delegate];
</syntaxhighlight>
</syntaxhighlight>


== APP SDK Error & Event Codes ==
== APP SDK Error & Event Codes ==
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 ==
=== Handling JSON Metadata ===
All the SDK methods handles only two types of objects: NSString, NSDictionary. The parameters passed must be either a JSON formatted string or a NSDictionary object. The JSON passed in the SDK must be well-formed.
* NSDictionary object
** If an object of unexpected type is passed to the method, the error message will be logged.
** If string has invalid JSON format, the error message will be logged.
* JSON value must be string value.
** This includes boolean and numeric values. For example, a value of true should be represented with "true", number value 123 should be "123".
** All the Variable Names like appid, appname, sfcode, dataSrc, title, type etc. are case-sensitive. Use the correct variable name as specified in the documentation.
* JSON string can be prepared using either raw NSString or serialized NSDictionary.
{{ExampleCode|
|Swift =
<syntaxhighlight lang="swift">
      let channelInfo = [
            "channelName": "My Channel Name 1",
];
       
        let contentMetadata = [
                "type": "content",
                "assetid": "88675545",
                "title": "Program S3, EP1",
                "isfullepisode":"n",
                "adloadtype":"2",
                "program":"Program Name",
                "length":"3600",
                "airdate":"20171020 10:05:00"
];
</syntaxhighlight>   
|Objective C = <syntaxhighlight lang="objective-c">
NSDictionary  *channelInfo = @
{
  @"channelName":@"My Channel Name 1",
}


NSDictionary *contentMetadata = @
== Interaction with APP SDK ==
  {@"type": @"content",
 
  @"assetid": [NSString stringWithFormat:@"ProgramAssetId-%d", i],
=== Configure Payload ===
  @"length": @"3600",
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
  @"program", "Program Name",
<syntaxhighlight lang="javascript">
  @"title": @"Program S3, EP1",
let metadata = {
  @"isfullepisode": @"y",
    'type':'content',
  @"adloadtype": "2",
    'assetid':'asset12345',
  @"airdate": "20161013 20:00:00"
    'program':'My Program',
}
    'title':'My Title',
</syntaxhighlight>
    'length':'42',
|Android = <syntaxhighlight lang="java">
    'airdate':'20180302 16:32:00',
JSONObject channelInfo = new JSONObject()
    'isfullepisode':'n',
    .put("channelname","My Channel Name 1")
    'adloadtype':'2'
};
</syntaxhighlight>  


JSONObject contentMetadata = new JSONObject()
The following section will explain the different values.
//SDK Metadata
    .put("type", "content")
    .put("assetid", "vid345-67483")
    .put("program", "Program Name")
    .put("title", "Program S3, EP1")
    .put("length", "3600")
    .put("isfullepisode", "y")
    .put("adloadtype", "2")
    .put("airdate", "20161013 20:00:00")
</syntaxhighlight> 
}}


=== Configure metadata ===  
==== 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 618: 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 627: 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 633: 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 647: 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 658: 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 666: Line 1,460:
! Type !! Sample code !! Description
! Type !! Sample code !! Description
|-
|-
|On App Start||<code>[nielsenMeter 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>[nielsenMeter 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>[nielsenMeter 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>[nielsenMeter 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>[nielsenMeter 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 684: 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 696: 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.
{{ExampleCode|
<syntaxhighlight lang="javascript"> NativeModules.NielsenAppApiBridge.play(sdk_id, channelInfo);</syntaxhighlight>
|Objective C = <syntaxhighlight lang="objective-c">   [nielsenAppApi play:(JSONObject channelInfo)];</syntaxhighlight>
 
|Android = <syntaxhighlight lang="java">    public void play(JSONObject channelInfo);</syntaxhighlight>
 
|Swift = <syntaxhighlight lang="swift">nielsenAppApi?.play(JSONObject channelInfo);</syntaxhighlight>
==== 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.
<syntaxhighlight lang="javascript">   NativeModules.NielsenAppApiBridge.loadMetadata(sdk_id, contentMetadata);</syntaxhighlight>


=== loadMetadata ===
{{ExampleCode|
|Objective C = <syntaxhighlight lang="objective-c">– (void)loadMetadata:(id)contentMetadata;</syntaxhighlight>
|Android = <syntaxhighlight lang="java">public void loadMetadata(JSONObject contentMetadata);</syntaxhighlight>
|Swift = <syntaxhighlight lang="swift">self.nielsenAppApi?.loadMetadata(contentMetadata)</syntaxhighlight>
}}


=== playheadPosition ===
==== playheadPosition ====
{{ExampleCode|
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.
|Objective C = <syntaxhighlight lang="objective-c">
<syntaxhighlight lang="javascript">   NativeModules.NielsenAppApiBridge.setPlayheadPosition(sdk_id, playheadPos);</syntaxhighlight>
(void) playheadPosition: (long long) playheadPos
</syntaxhighlight>


==== Sending playheadposition for content ====
<syntaxhighlight lang="objective-c">
AVPlayer *player;
CMTime curTime=[player currentTime];
int pos = CMTimeGetSeconds(curTime);
[nAppApiObject playheadPosition:pos];
</syntaxhighlight>


|Swift = <syntaxhighlight lang="swift">
==== stop ====
        //Monitor the Playhead position of the AVPlayer
Tell the SDK that content playback has stopped.
        let timeInterval: CMTime = CMTimeMakeWithSeconds(1.0,10)
<syntaxhighlight lang="javascript"> NativeModules.NielsenAppApiBridge.stop(sdk_id); </syntaxhighlight>
        self.avPlayerViewController.player?.addPeriodicTimeObserver(forInterval: timeInterval, queue: DispatchQueue.main) {(elapsedTime: CMTime) -> Void in
            if self.avPlayerViewController.player!.currentItem?.status == .readyToPlay {
                let time : Float64 = self.avPlayerViewController.player!.currentTime().seconds;
                let pos = Int64(time);
                NSLog("New Elapse Time = \(time)");
                self.nielsenAppApi?.playheadPosition(pos);
            }
        }
    }
</syntaxhighlight>
|Android = <syntaxhighlight lang="java">
public void setPlayheadPosition(long position)
</syntaxhighlight>
}}


=== stop ===
{{ExampleCode|
|Objective C = <syntaxhighlight lang="objective-c">– (void) stop</syntaxhighlight>
|Android = <syntaxhighlight lang="java">public void stop()</syntaxhighlight>
|Swift = <syntaxhighlight lang="swift">self.nielsenAppApi?.stop</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).
{{ExampleCode|
<syntaxhighlight lang="javascript">   NativeModules.NielsenAppApiBridge.end(sdk_id); </syntaxhighlight>
|Objective C = <syntaxhighlight lang="objective-c">- (void) end;</syntaxhighlight>
|Android = <syntaxhighlight lang="java">public void stop()</syntaxhighlight>
|Swift = <syntaxhighlight lang="swift">self.nielsenAppApi?.stop</syntaxhighlight>
}}


== Privacy and Opt-Out ==
=== Privacy and Opt-Out ===
{{ExampleCode|


iOS|
==== Opt-Out Implementation ====
== iOS 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 the optOutURL property of the SDK object <code>optOutURL</code> 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 App SDK returns NULL in the optOutURL, handle the exception gracefully and retry later.
*If the returned value is null or empty, handle the exception gracefully and retry later.
*To retrieve the current Opt-Out status of a device, use the [[optOutStatus]] method.


<!-- === Displaying Opt-Out in a WebView ===
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="objective-c">NielsenAppApi nAppApiObject;
@property(strong) UIWebView *optOutView;


// create WebView and set self as delegate
<syntaxhighlight lang="javascript">
self.optOutView=[[UIWebViewalloc]initWithFrame:self.view.bounds];
  var optoutUrlListner = eventEmitter.addListener(
 
    "EVENT_OPTOUT_URL",
self.optOutView.scalesPageToFit = yes;
    (data) => {
// get Nielsen defined web address and load the page
      console.log("EVENT_OPTOUT_URL :" + data.optouturl);
NSString *webAddress = nAppApiObject.optOutURL;
     }
 
  );
if(webAddress == nil)
  NativeModules.NielsenAppApiBridge.userOptOutURLString(sdk_id);  
     { // Handle it gracefully and retry later}
</syntaxhighlight>
else
{
    [optOutView loadRequest:[NSURLRequest requestWithURL:webAddress]];
    // show the view to the user
    [self.view addSubview:optOutView];
}</syntaxhighlight>
-->


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.
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.
Line 796: Line 1,534:
[[File:Privacy policy iOS.jpg|link=]]
[[File:Privacy policy iOS.jpg|link=]]


*URL to this web page should be called from SDK and opened in 'WebView' / External browser.
*If the App SDK returns NULL as Opt-Out URL, handle this case and retry later.
*To retrieve the current Opt-Out status, use the [[optOutStatus]] property from Nielsen's SDK API.
<syntaxhighlight lang="objective-c">
@property (readonly) BOOL optOutStatus;
</syntaxhighlight>
*App should provide a UI control like 'close' or 'back' button to close the 'WebView' / External browser.
*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'''.
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'''.
Line 812: 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>
|Android =
== Android 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.
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 to this web page should be called from SDK by invoking <code>userOptOutURLString()</code> and opened in 'WebView' / External browser.
<syntaxhighlight lang="java">
public String userOptOutURLString()
</syntaxhighlight>
*If the App SDK returns NULL as Opt-Out URL, handle the exception gracefully and retry later.
*To retrieve the current Opt-Out status of a device, use the <code> getOptOutStatus() </code> method.
<syntaxhighlight lang="java">
public boolean getOptOutStatus()
</syntaxhighlight>
=== Displaying Opt-Out in a WebView ===
<syntaxhighlight lang="java">
optOutUrl = mAppSdk.userOptOutURLString();
if(optOutUrl !=null)
{
  mWebView = (WebView) findViewById(R.id.webView);
  mWebView.getSettings().setJavaScriptEnabled(true);
  mWebView.getSettings().setBuiltInZoomControls(true);
  mWebView.getSettings().setDisplayZoomControls(false);
  mWebView.getSettings().setLoadWithOverviewMode(true);
  mWebView.getSettings().setUseWideViewPort(true);
  mWebView.setWebViewClient(new MonitorWebView());
  mWebView.setWebChromeClient(new WebChromeClient());
  mWebView.loadUrl(optOutUrl);
}
else
{
  //Handle it gracefully and Retry later
}
</syntaxhighlight>
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.
[[File:Privacy policy iOS.jpg|link=]]
<blockquote>'''Note:''' When ‘WebView’ / External browser is closed, do not pass the status returned from ‘WebView’ / External browser to the SDK within the app, as the new Opt-Out page will not return any response.</blockquote>
<blockquote>'''Note:''' App SDK manages the user’s choice (Opt-Out / Opt-In), the app does not need to manage this status.</blockquote>
Starting from SDK version 5.1.1.18:
*SDK will be sending the data pings to census even though SDK is opted out (In earlier releases all the traffic from SDK to census will be ceased). However, all the outgoing pings will have the parameter uoo=true using which backend can ignore this data.
*Current Opt-Out page is now updated to have no hyperlinks for Opt-Out / Opt-In operations. SDK Opt-Out has to be done via
'''Google Settings → Ads → Opt out of Ads Personalization'''.
<blockquote>'''Note:''' For Amazon devices, see [[#Opt-Out Implementation for Amazon Devices|Opt-Out Implementation for Amazon Devices]] below.</blockquote>
[[File:andr-ads.jpg|link=]]
<blockquote>'''Note:''' The 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>
== Opt-Out Implementation for Amazon Devices ==
Amazon device users can opt out or opt back into Nielsen Measurement, any time using the device’s setting – 'Limit Ad Tracking' (Interest-based ads).
User is opted out of Nielsen Online Measurement when ‘Limit Ad Tracking’ is enabled.
'''For devices running on Fire OS 5.1 and above, retrieve the Ad tracking value.'''
=== Retrieving Ad tracking Value ===
<syntaxhighlight lang="java">
ContentResolver cr = getContentResolver();
int limitAdTracking = Secure.getInt(cr, "limit_ad_tracking", 2);
</syntaxhighlight>
*Returns limit_ad_tracking value "0" if enabled
*Returns limit_ad_tracking value "1" if disabled
*Returns limit_ad_tracking value "2" if ad tracking is not supported (below Fire OS 5.1).
<blockquote>'''Note:''' Google Play Services are not needed to retrieve ad tracking state on Amazon devices. Limit Ad Tracking can be accessed through '''Settings → Apps & Games → Advertising ID'''.</blockquote>
}}


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


# '''Debug Logging''': Disable logging by deleting <code>{nol_sdkDebug: 'DEBUG'}</code> from initialization call.
# '''Debug Logging''': Disable logging by deleting <code>{nol_devDebug: 'DEBUG'}</code> from initialization call.
#* '''Example Production Initialization Call''' - Refer to the production initialization call below:
#* '''Example Production Initialization Call''' - Refer to the production initialization call below:


'''<big>iOS Example:</big>'''
'''<big>Example:</big>'''


<syntaxhighlight lang="swift">
<syntaxhighlight lang="javascript">
class NielsenInit: NSObject {
     let appInformation = {
    class func createNielsenAppApi(delegate: NielsenAppApiDelegate) -> NielsenAppApi?{
             "appid": "PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX","intType": "r"
     let appInformation:[String: String] = [
             "appid": "PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
            "sfcode": "it"
            // Remove Flag:  "nol_devDebug": "DEBUG"
        ]
        return NielsenAppApi(appInfo:appInformation, delegate:delegate)
    }
}
</syntaxhighlight>
 
 
'''<big>Android Example:</big>'''
<syntaxhighlight lang="java"> 
try
{
  // Prepare AppSdk configuration object (JSONObject)
  JSONObject appSdkConfig = new JSONObject()
          .put("appid", "PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
          .put("sfcode", "it")
             // Remove Flag:  "nol_devDebug": "DEBUG"
             // Remove Flag:  "nol_devDebug": "DEBUG"
 
    };
// Pass appSdkConfig to the AppSdk constructor
    NativeModules.NielsenAppApiBridge.createInstance(appInformation);
mAppSdk = new AppSdk(appContext, appSdkConfig, appSdkListener);
}
catch (JSONException e)
{
  Log.e(TAG, "Couldn’t prepare JSONObject for appSdkConfig", e);
}
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 22:06, 26 June 2020

Engineering Portal / Digital / DCR & DTVR / 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);