DCR React Native Integration: Difference between revisions
From Engineering Client Portal
ColinBrown (talk | contribs) |
ColinBrown (talk | contribs) |
||
(4 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
{{Breadcrumb|}} {{Breadcrumb|Digital}} {{Breadcrumb| | {{Breadcrumb|}} {{Breadcrumb|Digital}} {{Breadcrumb|DCR & DTVR}} {{CurrentBreadcrumb}} | ||
[[Category:Digital]] | [[Category:Digital]] | ||
<br/> | <br/> | ||
Line 7: | Line 7: | ||
<br/> | <br/> | ||
[[DCR_React_Native_WebView_Integration|Integrate Nielsen SDK in React-Native Webview App]] | [[DCR_React_Native_WebView_Integration|Integrate Nielsen SDK in React-Native Webview App]] | ||
= Integrate Nielsen SDK Legacy Api in React-Native App = | = Integrate Nielsen SDK Legacy Api in React-Native App = | ||
Line 203: | Line 204: | ||
@synchronized (self) { | @synchronized (self) { | ||
NSMutableDictionary *bridgedInfo = [NSMutableDictionary dictionaryWithDictionary:appInfo]; | 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)]; | NSString *sdk_id = [NSString stringWithFormat:@"%lli", (long long)([[NSDate date] timeIntervalSince1970] * 1000)]; | ||
bridgedInfo[ | bridgedInfo[@"nol_playerid"] = sdk_id; | ||
NielsenAppApi *nlsSDK = [[NielsenAppApi alloc] initWithAppInfo:bridgedInfo delegate:self]; | NielsenAppApi *nlsSDK = [[NielsenAppApi alloc] initWithAppInfo:bridgedInfo delegate:self]; | ||
if (nlsSDK) { | if (nlsSDK) { | ||
Line 480: | Line 482: | ||
var bridgedInfo = appInfo | var bridgedInfo = appInfo | ||
// generate unique id to address created sdk instance | |||
let sdk_id = String(format: "%lli", CUnsignedLongLong(Date().timeIntervalSince1970 * 1000)) | let sdk_id = String(format: "%lli", CUnsignedLongLong(Date().timeIntervalSince1970 * 1000)) | ||
bridgedInfo[ | bridgedInfo["nol_playerid"] = sdk_id | ||
let nlsSDK = NielsenAppApi(appInfo: bridgedInfo, delegate: self) | let nlsSDK = NielsenAppApi(appInfo: bridgedInfo, delegate: self) | ||
if nlsSDK != nil { | if nlsSDK != nil { | ||
Line 836: | Line 839: | ||
{ | { | ||
Log.d(NIELSEN_TAG, "SDK instance created successfully"); | Log.d(NIELSEN_TAG, "SDK instance created successfully"); | ||
String id = | String id = String.valueOf(new Date().getTime()); | ||
mAppSdkInstances.put(id, mAppSdk); | mAppSdkInstances.put(id, mAppSdk); | ||
WritableMap params = Arguments.createMap(); | WritableMap params = Arguments.createMap(); | ||
Line 1,314: | Line 1,317: | ||
! Parameter / Argument !! Description !! Source !! Required? !! Example | ! 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. | | sfcode || Nielsen collection facility to which the SDK should connect. | ||
Line 1,346: | Line 1,351: | ||
); | ); | ||
let appInformation = {"appid": "PDA7D5EE6-B1B8-XXXX-XXXX-2A788BCXXXCA"}; | let appInformation = {"appid": "PDA7D5EE6-B1B8-XXXX-XXXX-2A788BCXXXCA","intType": "r"}; | ||
NativeModules.NielsenAppApiBridge.createInstance(appInformation); | NativeModules.NielsenAppApiBridge.createInstance(appInformation); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Line 1,549: | Line 1,554: | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
let appInformation = { | let appInformation = { | ||
"appid": "PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", | "appid": "PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX","intType": "r" | ||
// Remove Flag: "nol_devDebug": "DEBUG" | // Remove Flag: "nol_devDebug": "DEBUG" | ||
}; | }; | ||
NativeModules.NielsenAppApiBridge.createInstance(appInformation); | NativeModules.NielsenAppApiBridge.createInstance(appInformation); | ||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 22:06, 26 June 2020
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
|
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:
|
"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:
- 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.
- 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.
- 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.
- playheadPosition – Call this API every one second when playhead position timer is fired.
- stop – Call this API when the playback is paused, switches between content and ad (within the same content playback) or encounters interruptions.
- 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.
- As soon as the playback resumes, call loadMetadata and playheadPosition.
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.
- 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.
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.
- 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);