DCR Thailand Video iOS SDK: Difference between revisions

From Engineering Client Portal

(Created page with "{{Breadcrumb|}} {{Breadcrumb|Digital}} {{Breadcrumb|International}} {{CurrentBreadcrumb}} Category:Digital == Overview == The Nielsen SDK is one of multiple framework SD...")
 
No edit summary
 
(7 intermediate revisions by 3 users not shown)
Line 1: Line 1:
{{Breadcrumb|}} {{Breadcrumb|Digital}} {{Breadcrumb|International}} {{CurrentBreadcrumb}}
{{Breadcrumb|}} {{Breadcrumb|Digital}} {{Breadcrumb|International_DCR}} {{CurrentBreadcrumb}}
[[Category:Digital]]
[[Category:Digital]]


== Overview ==
== Overview ==
The Nielsen SDK is one of multiple framework SDKs that Nielsen provides to enable measuring live streaming and on-demand video content 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. 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 covers implementation steps for iOS using Xcode utilizing the Standard Nielsen SDK for DCR.
 
{{iOS_SpecialNotes_for_iOS14}}
 
{{iOS_SpecialNotes_for_iOS17}}


== Prerequisites ==
== Prerequisites ==
To start using the App SDK, the following details are required:
Before you start the integration, you will need:
* '''App ID (appid):''' Unique ID assigned to the player/site and configured by product.
{| class="wikitable"
* '''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.
! style="width: 15%;" | Item
If you do not have any of these prerequisites or if you have any questions, please contact our SDK sales support team.
! Description
! Source
|-style="background-color:#d0f6f8;"
|| '''App ID (appid)''' || Unique ID assigned to the player/site and configured by product. || Provided by Nielsen
|-style="background-color:#d0f6f8;"
|| '''Nielsen SDK''' || Includes SDK frameworks and '''sample implementation'''; ''See [[iOS SDK Release Notes]]'' || [[Special:Downloads|Download]]
|}
 
If need App ID(s) or our SDKs, feel free to reach out to us and we will be happy to help you get started.
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.


==  Implementation ==
==  Implementation ==
This guide covers implementation steps for iOS using Xcode.
Version 8 of the Nielsen App SDK will come in three versions. One that is enabled to work with the App Tracking Transparency Framework, another version that does not use the Ad Framework, and a version for Kids Apps or where noID is required.
 
{| class="wikitable"
|-
! SDK Flavor
! Description
|-
| '''iOS Ad Version'''
|* Opt-In and Opt-Out functionality managed by the [https://developer.apple.com/documentation/apptrackingtransparency AppTrackingTransparency framework] . '''(Preferred approach)''' <br />* The Nielsen SDK will attempt to collect the IDFA (Id for Advertisers) on the device.<br> * For iOS14+, if the value returned is <code>ATTrackingManager.AuthorizationStatus.authorized</code>.<br>*  If the device is running iOS12 or iOS13, the Limit Ad Tracking setting is requested.
|-
| '''iOS No Ad Framework'''
|* Without the Ad Framework, the Nielsen SDK cannot read the IDFA, so it will attempt to retrieve the '''IDFV'''.<br />* The [https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor ID for Vendors (IDFV)], may be used for analytics across apps from the same content provider.<br />* The developer is required to present the User Choice Opt Out page which is described in the [[DCR_Thailand_Video_iOS_SDK#Global_iOS_SDK_No_Ad_Framework_Optout|Privacy Section]].
|-
| '''iOS SDK noID'''
|* This version of the Nielsen SDK is perfect for Kid apps, or where no ID is required.<br>* Please review the [[DCR_Thailand_Video_iOS_SDK#Global_iOS_SDK_No_ID_Optout_.28Kids_Category.29|Opt Out Requirement]].
|}
=== How to obtain the NielsenAppApi.Framework ===
The Nielsen AppSDK can either be downloaded directly or can be integrated directly within an application through the use of CocoaPods. We recommend using the CocoaPods-based integration whenever possible to ensure you maintain the most recent changes and enhancements to the Nielsen libraries.
* [[Digital_Measurement_iOS_Artifactory_Guide|Select to obtain CocoaPods implementation guide]]
* [[Special:Downloads|Select to Download Directly]]
* [[DCR_Video_iOS_SDK_xcframework|Using the XCFramework bundle]]
 
__TOC__


== Setting up your  Development Environment  ==
== Setting up your  Development Environment  ==
<big>
Prior to SDK Version 6.2.0.0 the  IOS framework has been distributed as a static library packaged into framework bundle format. Apple recommends to use dynamic framework, it has some benefits over static libraries like less executable file size of an app, faster startup time and native support in xCode IDE. Nielsen AppSDK has been transformed into dynamic framework in this release ([[iOS_Static_Framework_Setup|static framework]] is still available).
'''Configuring Xcode Development Environment'''
</big>


Nielsen App SDK is compatible with Apple iOS versions 9.0 and above.
If migrating from the static library to this new dynamic framework, once implemented, unless your specific application requires, you can remove the following Frameworks that were once required:<code> [AdSupport, JavascriptCore, SystemConfiguration, Security, AVFoundation, libc++] </code>
<br>


The SDK uses the NSURLSession instead of the deprecated NSURLConnection.
The '''Dynamic framework''' is created as a fat framework. It means that it contains slices required for devices (armv7, arm64) as well as slices required for simulators (i386, x86_64). Simulator slices are needed to let clients build and debug their app on the simulators, but they should be removed before sending the app to the AppStore. The example of the shell script that should be added as a Run Script phase in the application can be [[DCR_Thailand_Video_iOS_SDK#Removing_Simulators_.28Dynamic_Framework_Only.29|found below]].


<blockquote>'''Note''': All communications between the SDK and the Census (Collection Facility) use HTTPS.</blockquote>
'''[[DCR_Video_iOS_SDK_xcframework|XCFramework]]''' is solution for the problems described above Apple recommends to use XCFrameworks. In XCFramework, we no longer build a single framework with multiple architectures. Instead, we build one small framework for each combination of architecture and target and store it in its own folder. The top-level XCFramework folder have folders like ios-arm64, ios-arm64-simulator, etc. Each of these folders is its own framework, complete with headers, modules, and binary.


<big>'''Importing Frameworks'''</big>
=== Configuring Xcode Development Environment ===
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.
Starting with SDK version 6.0.0.0, the Nielsen App SDK is compatible with Apple iOS versions 8.0 and above. In addition, when using the dynamic framework,  all the required frameworks are linked automatically as the are needed. More details can be found here: https://stackoverflow.com/questions/24902787/dont-we-need-to-link-framework-to-xcode-project-anymore
* 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
* CoreMedia.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'''
<blockquote>'''Note''': All communications between the SDK and the Census (Collection Facility) use HTTPS.</blockquote>
* 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 />
<big>'''Using Swift'''</big>
To import a set of Objective-C files in the same app target as your Swift code, you rely on an Objective-C bridging header to expose those files to Swift. Xcode offers to create this header file when you add a Swift file to an existing Objective-C app, or an Objective-C file to an existing Swift app.


Select File/New File/Objective-C File  <br />
=== Download Framework ===
Xcode will prompt you to create a bridging header.
The first step is to download and copy the [[Special:Downloads|NielsenAppApi.framework]] bundle to the app project directory. (''Not required if using CocaPods'')
[[File:bridgingheader 2x.png|600px|center|link=]] <br />
Once this file has been created, you need to add the following:
<syntaxhighlight lang="swift">
#import <NielsenAppApi/NielsenAppApi.h>
</syntaxhighlight>
<big>'''Using Objective-C'''</big>
Add the code
<syntaxhighlight lang ="objective-c">
#import <NielsenAppApi/NielsenAppApi.h>
</syntaxhighlight>
to the View Controller’s header file.
<br />


== SDK Initialization ==
=== Add Framework ===
The latest version of the Nielsen App SDK allows instantiating multiple instances of the SDK object, which can be used simultaneously without any issue. The sharedInstance API that creates a singleton object was deprecated prior to version 5.1.1. (Version 4.0 for Android)
In the General tab for app configuration add NielsenAppApi.framework in the list of Embedded Binaries. (''Not required if using CocaPods'')


* A maximum of four SDK instances per appid are supported. When a fifth SDK instance is launched, the SDK will return “nil” from [[initWithAppInfo:delegate:]]
=== Add Path ===
* When four SDK instances exist, you must destroy an old instance before creating a new one.
Add path to the NielsenAppApi.framework in the Framework Search Paths build setting. (''Not required if using CocaPods'')


The following table contains the list of arguments that can be passed via the AppInfo JSON schema.
=== Import Framework ===
Add NielsenAppApi.framework module in the source file of your app:


* The appid is provided by the Nielsen Technical Account Manager (TAM). The appid is a GUID data type and is specific to the application.
==== Using Swift ====
{| class="wikitable"
Add the following:
|-
! Parameter / Argument !! Description !! Source !! Required/Obligatory? !! Example
|-
| appid || Unique id for the application assigned by Nielsen. It is GUID data type.|| Nielsen-specified || ✓ || PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
|-
| appversion || Current version of the app used || Client-defined || No || "1.0.2"
|-
| sfcode || Nielsen collection facility to which the SDK should connect.
|| Nielsen-specified || ✓ || "dcr"
|-
| nol_devDebug || Enables Nielsen console logging. Only required for testing
|| Nielsen-specified || Optional || "DEBUG"
|}
<br />
==== Sample SDK Initialization Code ====
Swift 4.0 Example:
<code>NielsenInit.swift</code>
<syntaxhighlight lang="swift">
<syntaxhighlight lang="swift">
class NielsenInit: NSObject {
import NielsenAppApi
    class func createNielsenAppApi(delegate: NielsenAppApiDelegate) -> NielsenAppApi?{
    let appInformation:[String: String] = [
          "appid": "PDA7D5EE6-B1B8-XXXX-XXXX-2A788BCXXXXX",
            "appversion": "1.0",
            "sfcode": "dcr",
            "nol_devDebug": "DEBUG"
        ]
        return NielsenAppApi(appInfo:appInformation, delegate:delegate)
    }
}
</syntaxhighlight>
</syntaxhighlight>


 
==== Using Objective-C ====
Sample code using AVPlayer.
<syntaxhighlight lang ="objective-c">
<br />
@import NielsenAppApi;
<code>ViewController.swift</code>
 
<syntaxhighlight lang="swift">
class ViewController: UIViewController, NielsenAppApiDelegate, AVPictureInPictureControllerDelegate, CLLocationManagerDelegate  {
   
    let avPlayerViewController = AVPlayerViewController()
    var avPlayer:AVPlayer?
    var nielsenAppApi: NielsenAppApi!
 
  override func viewDidLoad() {
        super.viewDidLoad()
 
self.nielsenAppApi = NielsenInit.createNielsenAppApi(delegate: self)
NSLog("Nielsen SDK initialized")
 
            }
  }
</syntaxhighlight>
</syntaxhighlight>


== APP SDK Error & Event Codes ==
{{iOS_SDK_Initialization}}
To view the Error and Event codes for iOS, please review the [[APP SDK Event Codes|App SDK Event Code]] Reference page.


== Configure Payload ==
== Configure Metadata ==
=== 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.
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
* NSDictionary object
Line 143: Line 102:
* JSON value must be string value.
* 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".
** 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.
** All the Nielsen Key names (e.g. appid, program) 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.
* JSON string can be prepared using either raw NSString or serialized NSDictionary.
 
<br>
<syntaxhighlight lang="swift">
=== Create channelName Metadata ===
      let channelInfo = [
            "channelName": "My Channel Name 1",
];
       
        let contentMetadata = [
                "type": "content",
                "assetid": "88675545",
                "title": "Program S3, EP1",
                "isfullepisode": "n",
                "adloadtype": "2",
                "SegmentB": "custom",
                "SegmentC": "custom",
                "program": "Program Name",
                "length": "3600"
];
</syntaxhighlight>
 
=== Configure metadata ===  
channelName should remain constant throughout the completion of an episode or live stream.
channelName should remain constant throughout the completion of an episode or live stream.
<br />
<br />
Line 174: Line 115:
|-
|-
|}
|}
<br/>
=== Create Content Metadata ===
Content metadata should remain constant throughout the entirety of an episode/clip including when ads play.
<blockquote> program and title metadata values should be passed to SDK as UTF-8 strings. </blockquote>
{| class="wikitable"
|-
! Key !! Description !! Values !! Required
|-
| clientid ||
parent ID – value is automatically populated through provided App ID.<br/>
In order to override the brand configured to the App ID, pass parent <br/>
value here and the sub-brand ID associated to that brand in the subbrand <br/>
key (e.g. multiple brands in App)
||
Nielsen provided
||
|-
| subbrand || sub-brand ID – value is automatically populated through provided<br/>
App ID. In order to override the sub-brand configured to the App ID, value can <br/>
be passed here (e.g. multiple sub-brands in App)
||
Nielsen provided
||
|-
| type || type of asset || "content" || ✓
|-
| assetid || unique ID assigned to asset || custom<br>(no [[Special Characters]]). The Content ID should be populated here which should correspond to the same value in the post transmission logs. || ✓
|-
| program || name of program || custom || ✓
|-
| title || episode name || custom || ✓
|-
| length || length of content in seconds || seconds (86400 for live stream)|| ✓
|-
| segB || custom segment B. Custom segments can be used to aggregate content however you choose. Some examples include genre, category, or platform. || custom ||
|-
| segC || For VOD: Populate TVContent ID, For livestream: leave blank || custom || Required for VOD only
|-
|-
| isfullepisode || full episode flag ||
*'y', 'yes', or 'lf' – full episode
*'n', 'no', or 'sf' – non full episode
'''Note:''' For livestream content with Dynamic Ad Insertion (DAI), the isfullepisode value should be set to 'y'.
||
|-
|adloadtype || type of Ad load:
* 1) Linear – matches TV Ad load. Content with linear Ad Load is not eligible for DCR measurement and will not be included in DCR reporting.
* 2) Dynamic – Dynamic Ad Insertion (DAI)
||
*"1" – content with linear Ads. Note: Content with linear Ad load is not included in DCR measurement.
*"2" – content with dynamic Ads
||
|-
|}


=== Content Metadata (VOD) ===
==== Metadata Example ====
Content metadata should remain constant throughout the completion of an episode / clip including the ads play.
<code>Swift</code>
<table>
<syntaxhighlight lang="swift">
<tr>
<th> Keys </th>
<th> Description </th>
<th> Example </th>
<th> Required
</th></tr>
<tr>
<td>'''type'''</td>
<td><code>'content', 'ad'</code></td>
<td> <code> 'content'</code> </td>
<td> Yes
</td></tr>
<tr>
<td> '''assetid''' </td>
<td> unique ID assigned to asset </td>
<td> custom </td>
<td> Yes
</td></tr>
<tr>
<td> '''program''' </td>
<td>name of program (25 character limit) </td>
<td> custom </td>
<td> Yes
</td></tr>
<tr>
<td> '''title''' </td>
<td>name of program (40 character limit) </td>
<td> custom </td>
<td> Yes
</td></tr>
<tr>
<td> '''length''' </td>
<td> length of content in seconds </td>
<td> <code>seconds</code> </td>
<td> Yes
</td></tr>
<tr>
<td> '''isfullepisode''' </td>
<td> full episode flag</td>
<td> "y"- full episode, "n"- non full episode</td>
<td> Yes
</td></tr>
<tr>
<td> <b>adloadtype</b>
</td>
<td> ad model only pass value as 2
</td>
<td> 2
</td>
<td>Yes
</td></tr>
<tr>
<td> '''segB''' </td>
<td> custom segment B</td>
<td> custom </td>
<td>
</td></tr>
<tr>
<td> '''segC''' </td>
<td> custom segment C</td>
<td> custom </td>
<td>
</td></tr>
<tr>
<td> '''crossId1''' </td>
<td> standard episode ID </td>
<td> custom </td>
<td>
</td></tr>
<tr>
<td> '''crossId2 '''</td>
<td> content originator (only required for distributors) </td>
<td> Nielsen provided </td>
<td>
</td></tr>
 
</table>
<br />


==== Example Content Object (VOD) ====
<syntaxhighlight lang="swift"">
let contentMetadata = [
let contentMetadata = [
                "type": "content",
    "type": "content",
                "assetid": "88675545",
    "assetid": "C77664",
                "title": "Program S3, EP1",
    "title": "Program S2, E3",
                "isfullepisode": "n",
    "isfullepisode": "y",
                "adloadtype": "2",
    "program": "Program Name",
                "SegmentB": "custom",
    "length": "3600",
                "SegmentC": "custom",
    "adloadtype": "2",
                "program": "Program Name",
    "segB": "CustomSegmentValueB", //optional
                "length": "3600"  
    "segC": "CustomSegmentValueC", //optional
];
];
</syntaxhighlight>
<br>
<code>Objective-C</code>   
<syntaxhighlight lang="objective-c">
NSDictionary * contentMetadata = @ {
    @ "type": @ "content",
    @ "assetid": @ "C77664",
    @ "title": @ "S2,E3",
    @ "isfullepisode": @ "y", 
    @ "program": @ "Program Name",
    @ "length": @ "3600",
    @ "adloadtype": @ "2",
    @ "segB": @ "CustomSegmentValueB", //optional
    @ "segC": @ "CustomSegmentValueC", //optional
}
</syntaxhighlight>
</syntaxhighlight>
 
<!--
<br/>
=== Configure metadata ===  
==== Content Metadata (Live Streaming)====
channelName should remain constant throughout the completion of an episode or live stream.
Content metadata should remain constant throughout the completion of an episode / clip including the ads play.
{| class="wikitable"
<table>
|-
<tr>
! Key !! Description !! Values !! Required
<th> Keys </th>
|-
<th> Description </th>
| channelName || ChannelInfo refers to the Channel name. This can be a free-form value
<th> Example </th>
value such as a friendly name for the content being played. the SDK<br/>
<th> Required
will pass the application name automatically.
</th></tr>
|| custom || No
<tr>
|-
<td>'''type'''</td>
|}
<td><code>'content', 'ad'</code></td>
-->
<td> <code> 'content'</code> </td>
<td> Yes
</td></tr>
<tr>
<td> '''assetid''' </td>
<td> unique ID for each quarter </td>
<td> live021 </td>
<td> Yes
</td></tr>
<tr>
<td> '''program''' </td>
<td>name of program (25 character limit) </td>
<td> "CH Live" </td>
<td> Yes
</td></tr>
<tr>
<td> '''title''' </td>
<td>Use period as title name per each quarter </td>
<td>”02.00-02.14”</td>
<td> Yes</td></tr>
<tr>
<td> '''length''' </td>
<td> length of content in seconds </td>
<td>  900 </td>
<td> Yes
</td></tr>
<tr>
<td> '''isfullepisode''' </td>
<td> full episode flag</td>
<td> 'y'- full episode</td>
<td> Yes
</td></tr>
<tr>
<td> <b>adloadtype</b>
</td>
<td> ad model (only pass value as 2)
</td>
<td> '2'</td>
<td>Yes
</td></tr>
<tr>
<td> '''segB''' </td>
<td> custom segment B</td>
<td> custom </td>
<td>
</td></tr>
<tr>
<td> '''segC''' </td>
<td> custom segment C</td>
<td> custom </td>
<td>
</td></tr>
<tr>
<td> '''crossId1''' </td>
<td> standard episode ID </td>
<td> custom </td>
<td>
</td></tr>
<tr>
<td> '''crossId2 '''</td>
<td> content originator (only required for distributors) </td>
<td> Nielsen provided </td>
<td>
</td></tr>
</table>
 
==== Example Content Object (Live Streaming)====
<syntaxhighlight lang="swift"">
let contentMetadata = [
  type:      'content',
  assetid:  'live021',
  program:  'CHLive',
  title:    '02.00-02.14',
  length:    '900',
  isfullepisode: 'y',
  adloadtype:'2'
];
</syntaxhighlight>
 
<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.
<br/>
{| class="wikitable"
{| class="wikitable"
|-
|-
! Keys !! Description !! Values !! Required
! Keys !! Description !! Values !! Required
|-
|-
| type || type of ad || 'preroll', 'midroll', or 'postroll' || ✓
| type || type of Ad || <code>'preroll'</code>, <code>'midroll'</code>, <code>'postroll'</code> <br> <code>'ad'</code>  - If specific type can not be identified.|| ✓
|-
|-
| assetid || unique ID assigned to ad || custom || ✓
| assetid || unique ID assigned to Ad || custom <br>(no [[Special Characters]]) || ✓
|}
|}


==== Example Ad Object ====
==== Example Ad Object ====
 
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="swift"">
// create Ad object
let adMetadataObject = [
"ad": {
   assetid: 'AD-1',
   "type": "preroll",
   type:   'preroll'
   "assetid": "AD-ID123"
];
}
</syntaxhighlight>
</syntaxhighlight>


<br/>
{{iOS_LifeCycle_of_SDK}}


== Configure API Calls ==
== Configure API Calls ==
<!--[[File:appsdkTimeline-DCR.png|icon|link=]]-->
=== Sample API Sequence ===
A Sample API sequence could follow this flow:
{| class="wikitable"
|-
! Type !! Sample code !! Description
|-
| rowspan="2" | Start of stream || <code>nielsenMeter.play()</code> || // Call at start of each new stream
|-
| <code>nielsenMeter.loadMetadata(contentMetadata)</code> || // MetadataObject contains the JSON metadata<br> for the content being played
|-
| Content || <code>nielsenMeter.playheadPosition(pos);</code> || // playheadPosition is position of the playhead <br>while the content is being played
|-
| End of Stream || <code>nielsenMeter.end()</code> || // Content playback is completed.
|}
 
=== SDK Events ===
{| class="wikitable"
|-
! Event !! Parameter !! Description
|-
| 'play' || || Call at start of each new stream
|-
| 'loadMetadata' || content/ad metadata object || Needs to be called at the beginning of each asset
|-
| 'playheadPosition' || playhead position as integer<br/>
VOD: current position in seconds <br/>
Live: current UNIX timestamp (seconds since Jan-1-1970 UTC) <br/>
Note: 'PlayheadPosition' has to be called every second
||
Pass playhead position every second during playback
|-
| 'stop' || playhead position || Call during any interruption to content or Ad playback and at the end of each Ad.
|-
| 'end' || playhead position in seconds || Call when the current video asset completes playback and pass the playhead position. <br/>
Example: At the end of the content stream, if the user switches to another piece of content, when the browser is refreshed or closed.
|}
<blockquote>Note: For livestream, send the UNIX timestamp, for VOD send the time in seconds as integer. The final playhead position must be sent for the current asset being played before calling <code>'''stop'''</code>, <code>'''end'''</code> or<code> '''loadmetadata'''</code>,.</blockquote>


=== 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 '''Idle 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.
# '''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 an event to occur.
# '''Processing state''' – The SDK instance is processing playing information. [[#play|play]] and [[#Content_Metadata|loadMetadata]] calls move the SDK instance into this state. In this state, the SDK instance will be able to process the following calls.
# '''Processing state''' – The SDK instance is processing playing information. The <code>'''play'''</code> and <code>'''loadMetadata''' </code> calls move the SDK instance into this state. In this state, the SDK instance will be able to process the following calls.
## [[#play|playheadPosition]] – Call this API every one second when playhead position timer is fired.
## <code>'''playheadPosition'''</code> – Call this API every one second when playhead position is active.  If a LIVE event, use the current UNIX timestamp (seconds since Jan-1-1970 UTC).
## [[#stop|stop]] – Call this API when the playback is paused, switches between content and ad (within the same content playback) or encounters interruptions.
## <code>'''stop'''</code> – Call this API when the content or Ad playback is interrupted and at the end of each Ad.  
## [[#play|end]] – SDK instance exits from Processing state when this API is called.
## <code>'''end'''</code> Call when content completes. When called, the SDK instance exits from Processing state.
# '''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.
# '''Disabled state''' – The SDK instance is disabled and is not processing playing information.  
## Initialization fails
## <code>'''appDisableApi'''</code> is set to <code>true</code>
## <code>appDisableApi</code> is called


<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.
'''Note''': In case of any interruptions during playback due to alarm, calendar, call, flight mode, Wi-Fi toggle, channel change, etc., call [[#stop|stop]] to stop the measurement.
* As soon as the playback resumes, call [[#play|play]],  [[#Content_Metadata|loadMetadata]]  and  [[playheadPosition]].</blockquote>


=== API Call sequence ===
'''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 <code>'''loadMetadata''' </code> and  <code>'''playheadPosition'''</code> </blockquote>
 
=== API Call Sequence ===
==== Use Case 1: Content has no Advertisements ====
==== Use Case 1: Content has no Advertisements ====
Call [[#play|play()]] with channelName JSON as below.
Call [[play()]] at start of stream
<syntaxhighlight lang="json">{
 
  "channelName": "TheMovieTitle"
Call [[loadMetadata()]] with JSON metadata for content as below.
}</syntaxhighlight>
Call [[#Content_Metadata|loadMetadata()]] with JSON metadata for content as below.
<syntaxhighlight lang="json">{
<syntaxhighlight lang="json">{
   "type": "content",
   "type": "content",
Line 423: Line 308:
   ...
   ...
}</syntaxhighlight>
}</syntaxhighlight>
Call [[setPlayheadPosition()]] every one second until a pause / stop.
Call [[playheadPosition|playheadPosition()]] every one second until a pause / stop.
Use the sample API sequence below as a reference to identify the specific events that need to be called during content playback without ads.
Use the sample API sequence below as a reference to identify the specific events that need to be called during content playback without ads.
{| class="wikitable"
{| class="wikitable"
Line 429: Line 314:
! Type !! Sample code !! Description
! Type !! Sample code !! Description
|-
|-
| rowspan="2" | Start of stream || <code>mAppSdk.play(channelName); </code> || // channelName contains JSON metadata of channel/video name being played
| rowspan="2" | Start of stream || <code>mAppSdk.play(); </code> || // Call at start of each new stream
|-
|-
| <code>mAppSdk.loadMetadata(contentMetaDataObject);</code> || // contentMetadataObject contains the JSON metadata for the content being played
| <code>mAppSdk.loadMetadata(contentMetaDataObject);</code> || // contentMetadataObject contains the JSON metadata for the content being played
|-
|-style="background-color:#d8f5d7;"
| Content || <code>mAppSdk.setPlayheadPosition(playheadPosition);</code> || // position is position of the playhead while the content is being played
| Content || <code>mAppSdk.setPlayheadPosition(playheadPosition);</code> || // position is position of the playhead while the content is being played
|-
|-
| Interruption || <code>mAppSdk.stop();</code> || // call stop when content playback is interrupted
|-style="background-color:#d8f5d7;"
| rowspan="2" | Resume Content || <code>mAppSdk.loadMetadata(contentMetaDataObject);</code>  || // Call loadMetadata and pass content metadata object when content resumes
|- style="background-color:#d8f5d7;"
|<code>mAppSdk.setPlayheadPosition(playheadPosition);</code> || // continue pasing playhead position every second starting from position where content is resumed
|-
| End of Stream || <code>mAppSdk.end();</code> || // Content playback is completed.
| End of Stream || <code>mAppSdk.end();</code> || // Content playback is completed.
|}
|}


==== Use Case 2: Content has Advertisements ====
==== Use Case 2: Content has Advertisements ====
Call [[#play|play()]] with channelName JSON as below.
Call [[play()]] at start of stream
<syntaxhighlight lang="json">{
 
  "channelName": "TheMovieTitle"
Call [[loadMetadata()]] with JSON metadata for ad as below.
}</syntaxhighlight>
Call [[#Content_Metadata|loadMetadata()]] with JSON metadata for ad as below.
<syntaxhighlight lang="json">{
<syntaxhighlight lang="json">{
   "type": "preroll",
   "type": "preroll",
   "assetid": "ad=123"
   "assetid": "ad123"
}</syntaxhighlight>
}</syntaxhighlight>
<blockquote>Note: In case the individual ad details are not available, send ad pod (presence) details through the [[#Content_Metadata|loadMetadata]] and playhead position through [[playheadPosition]].</blockquote>
<blockquote>Note: In case the individual ad details are not available, send ad pod (presence) details through the [[loadMetadata]] and playhead position through [[playheadPosition]].</blockquote>


Call [[setPlayheadPosition()]] every one second until a pause / stop / another [[#Content_Metadata|loadMetadata()]] is called. Playhead should be passed for the entire duration of ad pod, if the ad pod details are passed as part of [[#Content_Metadata|loadMetadata()]].  
Call [[playheadPosition|playheadPosition()]] every one second until a pause / stop / another [[loadMetadata()]] is called. Playhead should be passed for the entire duration of ad pod, if the ad pod details are passed as part of [[loadMetadata()]].


The sample API sequence can be used as a reference to identify the specific events that need to be called during content and ad playback.
The sample API sequence can be used as a reference to identify the specific events that need to be called during content and ad playback.
Line 457: Line 346:
! Type !! Sample code !! Description
! Type !! Sample code !! Description
|-
|-
| rowspan="2" | Start of stream || <code>mAppSdk.play(channelName); </code> || // channelName contains JSON metadata of channel/video name being played
| rowspan="2" | Start of stream || <code>mAppSdk.play(); </code> || // stream starts
|-
|-
| <code>mAppSdk.loadMetadata(contentMetaDataObject);</code> || // contentMetadataObject contains the JSON metadata for the content being played
| <code>mAppSdk.loadMetadata(contentMetaDataObject);</code> || // contentMetadataObject contains the JSON metadata for the content being played
Line 463: Line 352:
| rowspan="3" | Preroll || <code>mAppSdk.loadMetadata(prerollMetadataObject);</code> || // prerollMetadataObject contains the JSON metadata for the preroll ad
| rowspan="3" | Preroll || <code>mAppSdk.loadMetadata(prerollMetadataObject);</code> || // prerollMetadataObject contains the JSON metadata for the preroll ad
|-
|-
| <code>mAppSdk.setPlayheadPosition(playheadPosition);</code> || // position is position of the playhead while the preroll ad is being played
| <code>mAppSdk.playheadPosition(playheadPosition);</code> || // position is position of the playhead while the preroll ad is being played
|-
|-
| <code>mAppSdk.stop();</code> || // Call stop after preroll occurs
| <code>mAppSdk.stop();</code> || // Call stop after preroll occurs
|-
|-
| rowspan="3" | Content || <code>mAppSdk.loadMetadata(contentMetaDataObject);</code> || // contentMetadataObject contains the JSON metadata for the content being played
| rowspan="2" | Content || <code>mAppSdk.loadMetadata(contentMetaDataObject);</code> || // contentMetadataObject contains the JSON metadata for the content being played
|-
| <code>mAppSdk.setPlayheadPosition(playheadPosition);</code> || // position is position of the playhead while the content is being played
|-
|-
| <code>mAppSdk.stop();</code> || // Call stop after the content is paused (ad starts)
| <code>mAppSdk.playheadPosition(playheadPosition);</code> || // position is position of the playhead while the content is being played
|-
|-
| rowspan="6" | Midroll || <code>mAppSdk.loadMetadata(midrollMetaDataObject);</code> || // midrollMetadataObject contains the JSON metadata for the midroll ad
| rowspan="3" | Midroll || <code>mAppSdk.loadMetadata(midrollMetaDataObject);</code> || // midrollMetadataObject contains the JSON metadata for the midroll ad
|-
|-
| <code>mAppSdk.setPlayheadPosition(playheadPosition);</code> || // position is position of the playhead while the midroll ad is being played
| <code>mAppSdk.playheadPosition(playheadPosition);</code> || // position is position of the playhead while the midroll ad is being played
|-
| <code>mAppSdk.stop();</code> || // App moves to background(midroll pauses)
|-
| <code>mAppSdk.loadMetadata(midrollMetaDataObject);</code> || // App moves to foreground (midroll resumes)
|-
| <code>mAppSdk.setPlayheadPosition(playheadPosition);</code> || // playheadPosition is position of the playhead while the midroll ad is being played  
|-
|-
| <code>mAppSdk.stop();</code> || // Call stop after midroll occurs
| <code>mAppSdk.stop();</code> || // Call stop after midroll occurs
|-
|-
| rowspan="3" | Content (End of stream) || <code>mAppSdk.loadMetadata(contentMetaDataObject);</code> || // contentMetadataObject contains the JSON metadata for the content being played
| rowspan="2" | Content Resumes || <code>mAppSdk.loadMetadata(contentMetaDataObject);</code> || // contentMetadataObject contains the JSON metadata for the content being played
|-
|-
| <code>mAppSdk.setPlayheadPosition(playheadPosition);</code> || // position is position of the playhead while the content is being played
| <code>mAppSdk.playheadPosition(playheadPosition);</code> || // position is position of the playhead while the content is being played
|-
|-
| End of Stream || <code>mAppSdk.end();</code> || // Call end() at the end of content
| End of Stream || <code>mAppSdk.end();</code> || // Call end() at the end of content
Line 493: Line 374:
| rowspan="3" | Postroll || <code>mAppSdk.loadMetadata(postrollMetaDataObject);</code> || // postrollMetadataObject contains the JSON metadata for the postroll ad
| rowspan="3" | Postroll || <code>mAppSdk.loadMetadata(postrollMetaDataObject);</code> || // postrollMetadataObject contains the JSON metadata for the postroll ad
|-
|-
| <code>mAppSdk.setPlayheadPosition(playheadPosition);</code> || // position is position of the playhead while the postroll ad is being played
| <code>mAppSdk.playheadPosition(playheadPosition);</code> || // position is position of the playhead while the postroll ad is being played
|-
|-
| <code>mAppSdk.stop();</code> || // Call stop after postroll occurs
| <code>mAppSdk.stop();</code> || // Call stop after postroll occurs
|}
|}


<blockquote>Note: Each Ad playhead should reset or begin from 0 at ad start. When content has resumed following an ad break, playhead position must continue from where previous content segment was left off.</blockquote>
<blockquote>Note: Each Ad playhead should begin from 0 at ad start. When content has resumed following an ad break, playhead position must continue from where previous content segment was left off.</blockquote>


=== Sequence Examples VOD ===
{{iOS_Sequence_of_Calls}}
The example code below will differ from your production application.  Provided to assist in explaining how to implement.


=== play ===
{{iOS_Foreground_and_Background}}
Use [[#play|play]] to pass the channel descriptor information through channelName parameter when the user taps the '''Play''' button on the player.
<syntaxhighlight lang="swift">nielsenAppApi?.play(JSONObject channelInfo);</syntaxhighlight>


=== loadMetadata ===
{{iOS_Interuptions_during_Playback}}
<syntaxhighlight lang="swift">self.nielsenAppApi?.loadMetadata(contentMetadata)</syntaxhighlight>


=== playheadPosition/setPlayheadPosition ===
{{iOS_NielsenAppSDKJSHandler}}
Please note: iOS sdk uses playheadPosition.  Android uses setPlayheadPosition.
 
<syntaxhighlight lang="swift">
{{iOS_PreCertification_Checklists}}
        //Monitor the Playhead position of the AVPlayer
 
        let timeInterval: CMTime = CMTimeMakeWithSeconds(1.0,10)
== Privacy and Opt-Out ==
        self.avPlayerViewController.player?.addPeriodicTimeObserver(forInterval: timeInterval, queue: DispatchQueue.main) {(elapsedTime: CMTime) -> Void in
 
            if self.avPlayerViewController.player!.currentItem?.status == .readyToPlay {
There are currently 3 flavors of the Nielsen SDK:
                let time : Float64 = self.avPlayerViewController.player!.currentTime().seconds;
# '''[[#Global_iOS_SDK_Opt-out|Global iOS SDK Opt-out]]''' - managed by ''AppTracking'' or ''Limit Ad Tracking'' setting on device ('''preferred approach''').
                let pos = Int64(time);
# '''[[#Global_iOS_SDK_No_Ad_Framework_Optout|Global iOS SDK No Ad Framework Optout]]''' - Direct call to SDK. Can be used without the Ad Framework
                NSLog("New Elapse Time = \(time)");
# '''[[#Global_iOS_SDK_No_ID_Optout_.28Kids_Category.29|Global iOS SDK No ID Optout]]''' - Direct call to SDK. Should be used for Kids Category.
                self.nielsenAppApi?.playheadPosition(pos);
            }
       
</syntaxhighlight>


=== stop ===
=== Global iOS SDK Opt-out ===
<syntaxhighlight lang="swift">self.nielsenAppApi?.stop</syntaxhighlight>
''OS-level Opt-out'' method available on Nielsen iOS


=== end ===
The Nielsen SDK automatically leverages the iOS's '''Limit Ad Tracking''' or '''AppTracking''' setting.
When content stop is initiated and content cannot be resumed from the same position (it can only be restarted from the beginning of stream).
*  If the User's device is running < iOS 13.x, the Nielsen SDK will check the status of '''Limit Ad Tracking'''.
<syntaxhighlight lang="swift">self.nielsenAppApi?.end</syntaxhighlight>
*  iOS14 modifies the way Apple manages the collection of a User's Opt-In status through '''AppTracking'''. Starting with Version 8.x+, the Nielsen App SDK will check the iOS version during initialization. If the device is running iOS12 or iOS13, the Limit Ad Tracking setting is requested. If iOS14.x +, then AppTracking is utilized.
==== Webview Element ====
It is a requirement to display a WebView element whose loadUrl is set to the value obtained from optOutURL.
If using the Global iOS SDK, this optOutURL informs the user how to deactivate/activate “App Tracking/Limit Ad Tracking”.


In addition, The following text must be included in your app store description.
<blockquote>"Please note: This app features Nielsen’s proprietary measurement software which contributes to market research, like Nielsen’s Digital Content Ratings. Please see https://www.nielsen.com/th/en/legal/privacy-statement/digital-measurement/ for more information"</blockquote>


=== Sequence Examples Live Streaming ===
=== Global iOS SDK No Ad Framework Optout ===
The example code below will differ from your production application. Provided to assist in explaining how to implement.
The ''User Choice'' method can be used without the Ad Framework, or in situations where the publisher does not wish to use the [https://developer.apple.com/documentation/apptrackingtransparency App Tracking Transparency Framework]. As this flavor of the Nielsen SDK does not use the Ad Framework, so it is necessary to display an Optout Page to the userand capture their selection.


=== play ===
Similar to the Global iOS SDK Flavor, it is a requirement to display a WebView element whose loadUrl is set to the
Use [[#play|play]] to pass the channel descriptor information through channelName parameter when the user taps the '''Play''' button on the player.
value obtained from optOutURL. This is a special URL that indicates Opt-in, or Opt-out and close the WebView.
<syntaxhighlight lang="swift">nielsenAppApi?.play(JSONObject channelInfo);</syntaxhighlight>


=== loadMetadata ===
==== This opt-out method works as follows: ====
Pass metadata for live streaming - Title will be dynamic depend on current time on device that user play the live streaming
* Get the Nielsen opt-out URL via [[optOutURL]]
<syntaxhighlight lang="swift">self.nielsenAppApi?.loadMetadata(contentMetadata)</syntaxhighlight>
* Display a WebView element whose loadUrl is set to the value obtained from [[optOutURL]]
* Detect if the WebView URL changes to a special URL that indicates Opt-in, or Opt-out and close the WebView
** Opt-out if the WebView URL = <code>nielsenappsdk://1</code>
** Opt-in if the WebView URL = <code>nielsenappsdk://0</code>
* Pass the detected URL to the [[userOptOut]] function
** Example: <syntaxhighlight lang=swift>NielsenAppApi?.userOptOut("nielsenappsdk://1"); // User opt-out</syntaxhighlight>


=== playheadPosition/setPlayheadPosition ===
=== Global iOS SDK No ID Optout (Kids Category) ===
Please note: iOS sdk uses playheadPosition. Android uses setPlayheadPosition.
If you are building an app that will be listed in the Kids Category:
  <syntaxhighlight lang="swift">
#  Ensure that you are using the [https://nielsendownloads-green.digitalengsdk.com/digital/Nielsen-iOS-App-SDK-GlobalNoId_latest.zip NoID version] of the Nielsen SDK Framework.
        //Monitor the Playhead position of the AVPlayer
# Immediately following the initialization of the Nielsen SDK ensure you call the userOptOut API with Opt out selection:
        let timeInterval: CMTime = CMTimeMakeWithSeconds(1.0,10)
<syntaxhighlight lang=swift>NielsenAppApi?.userOptOut("nielsenappsdk://1"); // User opt-out</syntaxhighlight>
        self.avPlayerViewController.player?.addPeriodicTimeObserver(forInterval: timeInterval, queue: DispatchQueue.main) {(elapsedTime: CMTime) -> Void in
            if self.avPlayerViewController.player!.currentItem?.status == .readyToPlay {
              var pos: TimeInterval
              pos = Date().timeIntervalSince1970
              self.nielsenAppApi?.playheadPosition(Int64(pos))
            }


</syntaxhighlight>
== Opt-out example code ==
===== Swift =====
<syntaxhighlight lang="swift">
import UIKit
import WebKit
import NielsenAppApi


=== When the quarter hour change ===
class OptOutVC: UIViewController, NielsenAppApiDelegate, WKNavigationDelegate {
    var nielsenApi : NielsenAppApi!
    var webView: WKWebView!
 
    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }


=== end ===
    override func viewDidLoad() {
Call end for the previous quarter hour.
        super.viewDidLoad()
<syntaxhighlight lang="swift">self.nielsenAppApi?.end</syntaxhighlight>


=== play ===
        if let appApi = self.nielsenApi {
Call play for start of new quarter hour
            //Getting the optPut URL from SDK
<syntaxhighlight lang="swift">nielsenAppApi?.play(JSONObject channelInfo);</syntaxhighlight>
            if let url = URL(string: appApi.optOutURL) {
                webView.load(URLRequest(url: url))
                webView.allowsBackForwardNavigationGestures = true
            }}}


=== loadMetadata ===
        func closeOptOutView() {
Call loadMetadata and pass content metadata for new quarter hour
            self.dismiss(animated: true, completion: nil)
<syntaxhighlight lang="swift">self.nielsenAppApi?.loadMetadata(contentMetadata)</syntaxhighlight>
        }
 
// Uncomment below code if you are using the Global iOS SDK No Ad Framework Flavor.  This will receive the user's selection
// From the custom User_Choice opt out page.  Only required for non-ad framework or no-id builds
// of the Nielsen SDK
/* 
        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler:
@escaping (WKNavigationActionPolicy) -> Void) {
            print(navigationAction.request.url?.absoluteString as Any) //For debugging to check what is being passed from webpage.
            if navigationAction.request.url?.absoluteString == "nielsen://close" {
                closeOptOutView()
                decisionHandler(.cancel)
            } else {
                if let url = navigationAction.request.url?.absoluteString, url.hasPrefix("nielsen") {
                    nielsenApi?.userOptOut(url). //either nielsenappsdk://1 or nielsenappsdk://0
                    decisionHandler(.cancel)
                } else {
                    if navigationAction.navigationType == .linkActivated {
                        if let url = navigationAction.request.url?.absoluteString, url.hasSuffix("#") {
                            decisionHandler(.allow)
                        } else {
                            decisionHandler(.cancel)
                            webView.load(navigationAction.request)
                        }
                    } else {
                        decisionHandler(.allow)
                    }}}}
  */
}


=== playheadPosition/setPlayheadPosition ===
Please note: iOS sdk uses playheadPosition.  Android uses setPlayheadPosition.
<syntaxhighlight lang="swift">
        //Monitor the Playhead position of the AVPlayer
        let timeInterval: CMTime = CMTimeMakeWithSeconds(1.0,10)
        self.avPlayerViewController.player?.addPeriodicTimeObserver(forInterval: timeInterval, queue: DispatchQueue.main) {(elapsedTime: CMTime) -> Void in
            if self.avPlayerViewController.player!.currentItem?.status == .readyToPlay {
                var pos: TimeInterval
              pos = Date().timeIntervalSince1970
              self.nielsenAppApi?.playheadPosition(Int64(pos))
            }
</syntaxhighlight>
</syntaxhighlight>
===== Objective-C =====
<syntaxhighlight lang="objective-c">


== Interruptions during playback ==
#import "OptOutVC.h"
As part of integrating Nielsen App SDK with the player application, the Audio / Video app developer needs to handle the following possible interruption scenarios:
#import "NielsenInit.h"
* Pause / Play
#import <NielsenAppApi/NielsenAppApi.h>
* Network Loss (Wi-Fi / Airplane / Cellular)
* Call Interrupt (SIM or Third party Skype / Hangout call)
* Alarm Interrupt
* Content Buffering
* Device Lock / Unlock (Video players only, not for Audio players)
* App going in the Background/Foreground (Video players only, not for Audio players)
* Channel / Station Change Scenario
* Unplugging of headphone
In case of encountering one of the above interruptions, the player application needs to
* Call [[#stop|stop]] immediately (except when content is buffering) and withhold sending playhead position.
* Start sending pings – [[#loadMetadata|loadMetadata]] and [[playheadPosition]] for the new viewing session, once the playback resumes.
Please see the [[Digital Measurement FAQ]] for more details


== Handling Foreground and Background states ==
@interface OptOutVC ()


For iOS, background/foreground detection is handled by the app lifecylce APIs which are provided by [https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/TheAppLifeCycle/TheAppLifeCycle.html Apple:]
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end


Foreground/Background state measurement is a requirement of Nielsen AppSDK implementation.
@implementation OptOutVC


== Privacy and Opt-Out ==
- (void)viewDidLoad {
    [super viewDidLoad];


Users must either have access to the "About Nielsen Measurement" page, or have similar text available within the native app. 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.
- (void)viewDidLoad {
    [super viewDidLoad];
    //Getting the optPut URL from eventTracker
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL
URLWithString:self.nielsenApi.optOutURL]]];
}
 
//Uncomment below code if you are using the Global iOS SDK No Ad Framework Flavor.
// From the custom User_Choice opt out page.  Only required for non-ad framework or no-id builds
// of the Nielsen SDK
/*   
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    if ([navigationAction.request.URL.absoluteString isEqualToString:kNielsenWebClose])
    {  [self performSelector:@selector(closeOptOutView) withObject:nil afterDelay:0];
        decisionHandler(WKNavigationActionPolicyCancel);
    } else {
        if ([navigationAction.request.URL.absoluteString hasPrefix:@"nielsen"])
        {[self.nielsenAppApi userOptOut:navigationAction.request.URL.absoluteString];
            decisionHandler(WKNavigationActionPolicyCancel);
        } else {
            if (navigationAction.navigationType == WKNavigationTypeLinkActivated)
            { if ([navigationAction.request.URL.absoluteString hasSuffix:@"#"])
                      {decisionHandler(WKNavigationActionPolicyAllow);
                } else {
                    decisionHandler(WKNavigationActionPolicyCancel);
                    [webView loadRequest:[NSURLRequest requestWithURL:navigationAction.request.URL]];
                }} else {
                decisionHandler(WKNavigationActionPolicyAllow);
            }}}
*/
}


* URL to this web page should be called from SDK by invoking  userOptOutURLString() and opened in 'WebView' / External browser.
* 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 userOptOutURLString() method.
<syntaxhighlight lang ="swift ">
public String userOptOutURLString()
public boolean getOptOutStatus()
</syntaxhighlight>
</syntaxhighlight>
<br>
Users can opt out or opt back into Nielsen Measurement. Opt-Out feature relies on the system setting – "Limit Ad Tracking". The setting can be accessed in the Settings application on any device. User is opted out of Nielsen online measurement research when the "Limit Ad Tracking" setting is enabled.


In addition, the following text must be included in your app store description.
== Retrieve current Opt-Out preference ==
 
Whether the user is opted out via OS-level Opt-out or via User Choice Opt-out, the current Opt-Out status as detected by the SDK is available via the [[optOutStatus]] property in the Nielsen SDK API
'''"Please note: This app features Nielsen’s proprietary measurement software which contributes to market research. Please see http://priv-policy.imrworldwide.com/priv/mobile/th/en/optout.html for more information"'''
<syntaxhighlight lang="objective-c">
@property (readonly) BOOL optOutStatus
</syntaxhighlight>


== Going Live ==
{{iOS_Airplay}}
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.
{{iOS_Going_Live}}
#* '''Example Production Initialization Call''' - Refer to the production initialization call below:


'''<big>iOS Example:</big>'''
{{iOS_Removing_Simulator_Slices}}


<syntaxhighlight lang="swift">
== Sample Applications ==
class NielsenInit: NSObject {
The below sample applications have been designed to show the Simplified API's functionality and are broken into two distinct categories:
    class func createNielsenAppApi(delegate: NielsenAppApiDelegate) -> NielsenAppApi?{
* '''Basic''' - To show the functionality of the Nielsen Simplified API using a standard no-frills player.
    let appInformation:[String: String] = [
** [[Swift Basic Sample|Swift 5.0 Sample]]
            "appid": "PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
** [[Objective-c Basic example|Objective-C Sample]]
            "sfcode": "dcr"
            // Remove Flag:  "nol_devDebug": "DEBUG"
        ]
        return NielsenAppApi(appInfo:appInformation, delegate:delegate)
    }
}
</syntaxhighlight>


'''Note''': before going live you have to inform Nielsen team - this is necessary, because Nielsen team has to adjust internal configuration parameter to enable data collection. Without that notification no data will be collected and no data will be reported.
* '''Advanced''' - Nielsen Simplified API integrated into a custom video player.

Latest revision as of 02:54, 27 March 2024

Engineering Portal / Digital / International_DCR / DCR Thailand Video iOS SDK

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. 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 covers implementation steps for iOS using Xcode utilizing the Standard Nielsen SDK for DCR.

Special Notes regarding iOS14

Permission to Track

Apple recently released a new policy on consent requirements, that require the user's permission, to track them using their device's advertising identifier (IDFA). To request the user's permission, use the AppTrackingTransparency framework. The ID for Vendors (IDFV), may be used for analytics across apps from the same content provider. The IDFV may not be combined with other data to track a user across apps and websites owned by other companies unless you have been granted permission to track by the user.

For more information, see:

More detailed information on how the Nielsen SDK versions work with the AppTrackingTransparency framework is located on our DCR Video iOS14 Migration page.

App store privacy questionnaire

As of April 22nd, 2021, any app submitted to the app store will need to provide information about your app's privacy practices, including the practices of third-party partners such as Nielsen, through App Store Connect. Nielsen has created a guide which is titled, User Privacy and Data Use to make information about Nielsen’s data collection practices available to clients who use the Nielsen Digital SDK and Nielsen tags. The guide is organized using headings of the App privacy details on the App Store (as of December 7th, 2020) webpage for convenience.

Special Notes regarding iOS17 or TVOS17

Beginning with iOS/TVOS 17, Apple is adding several requirements for App developers around tracking, use of Identifier For Advertisers (IDFA), and certain system APIs.

This requirement entails users manually opting in to declare all domains employed for tracking purposes, which includes the collection of IDFAs (Identifier for Advertisers). Currently, even if users choose not to opt in for tracking, it's essential to note that our Nielsen Digital SDKs continue to carry out measurements and transmit data without relying on IDFA. However, this new privacy measure introduced by Apple necessitates that we bring this development to your attention, as it could potentially impact your Nielsen measurement and tracking for iOS app usage.

In order to minimize the impact, we are asking that clients do the following:

  • Do not declare the Nielsen imrworldwide.com domain in the privacy manifest.
  • Update to the latest Nielsen SDK release >= 9.2.0.0 when compiling your app for iOS 17.

For any additional information please refer to the Nielsen global page: DCR and DTVR with iOS17 or TVOS17.

Prerequisites

Before you start the integration, you will need:

Item Description Source
App ID (appid) Unique ID assigned to the player/site and configured by product. Provided by Nielsen
Nielsen SDK Includes SDK frameworks and sample implementation; See iOS SDK Release Notes Download

If need App ID(s) or our SDKs, feel free to reach out to us and we will be happy to help you get started. Refer to Digital Measurement Onboarding guide for information on how to get a Nielsen App SDK and appid.

Implementation

Version 8 of the Nielsen App SDK will come in three versions. One that is enabled to work with the App Tracking Transparency Framework, another version that does not use the Ad Framework, and a version for Kids Apps or where noID is required.

SDK Flavor Description
iOS Ad Version * Opt-In and Opt-Out functionality managed by the AppTrackingTransparency framework . (Preferred approach)
* The Nielsen SDK will attempt to collect the IDFA (Id for Advertisers) on the device.
* For iOS14+, if the value returned is ATTrackingManager.AuthorizationStatus.authorized.
* If the device is running iOS12 or iOS13, the Limit Ad Tracking setting is requested.
iOS No Ad Framework * Without the Ad Framework, the Nielsen SDK cannot read the IDFA, so it will attempt to retrieve the IDFV.
* The ID for Vendors (IDFV), may be used for analytics across apps from the same content provider.
* The developer is required to present the User Choice Opt Out page which is described in the Privacy Section.
iOS SDK noID * This version of the Nielsen SDK is perfect for Kid apps, or where no ID is required.
* Please review the Opt Out Requirement.

How to obtain the NielsenAppApi.Framework

The Nielsen AppSDK can either be downloaded directly or can be integrated directly within an application through the use of CocoaPods. We recommend using the CocoaPods-based integration whenever possible to ensure you maintain the most recent changes and enhancements to the Nielsen libraries.

Setting up your Development Environment

Prior to SDK Version 6.2.0.0 the IOS framework has been distributed as a static library packaged into framework bundle format. Apple recommends to use dynamic framework, it has some benefits over static libraries like less executable file size of an app, faster startup time and native support in xCode IDE. Nielsen AppSDK has been transformed into dynamic framework in this release (static framework is still available).

If migrating from the static library to this new dynamic framework, once implemented, unless your specific application requires, you can remove the following Frameworks that were once required: [AdSupport, JavascriptCore, SystemConfiguration, Security, AVFoundation, libc++]

The Dynamic framework is created as a fat framework. It means that it contains slices required for devices (armv7, arm64) as well as slices required for simulators (i386, x86_64). Simulator slices are needed to let clients build and debug their app on the simulators, but they should be removed before sending the app to the AppStore. The example of the shell script that should be added as a Run Script phase in the application can be found below.

XCFramework is solution for the problems described above Apple recommends to use XCFrameworks. In XCFramework, we no longer build a single framework with multiple architectures. Instead, we build one small framework for each combination of architecture and target and store it in its own folder. The top-level XCFramework folder have folders like ios-arm64, ios-arm64-simulator, etc. Each of these folders is its own framework, complete with headers, modules, and binary.

Configuring Xcode Development Environment

Starting with SDK version 6.0.0.0, the Nielsen App SDK is compatible with Apple iOS versions 8.0 and above. In addition, when using the dynamic framework, all the required frameworks are linked automatically as the are needed. More details can be found here: https://stackoverflow.com/questions/24902787/dont-we-need-to-link-framework-to-xcode-project-anymore

Note: All communications between the SDK and the Census (Collection Facility) use HTTPS.

Download Framework

The first step is to download and copy the NielsenAppApi.framework bundle to the app project directory. (Not required if using CocaPods)

Add Framework

In the General tab for app configuration add NielsenAppApi.framework in the list of Embedded Binaries. (Not required if using CocaPods)

Add Path

Add path to the NielsenAppApi.framework in the Framework Search Paths build setting. (Not required if using CocaPods)

Import Framework

Add NielsenAppApi.framework module in the source file of your app:

Using Swift

Add the following:

import NielsenAppApi

Using Objective-C

@import NielsenAppApi;

SDK Initialization

The latest version of the Nielsen App SDK allows instantiating multiple instances of the SDK object, which can be used simultaneously without any issue. The sharedInstance API that creates a singleton object was deprecated prior to version 5.1.1. (Click here for an example of multiple instances)

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

Parameter / Argument Description Source Required? Example
appid Unique Nielsen ID for the application. The ID is a GUID data type. If you did not receive your App ID, let us know and we will provide you. Nielsen-specified Yes PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
nol_devDebug Enables Nielsen console logging. Only required for testing
Nielsen-specified Optional DEBUG

Debug flag for development environment

Player application developers / integrators can use Debug flag to check whether an App SDK API call made is successful. To activate the Debug flag, Pass the argument @"nol_devDebug":@"INFO", in the JSON string . The permitted values are:

  • INFO: Displays the API calls and the input data from the application (validate player name, app ID, etc.). It can be used as certification Aid.
  • WARN: Indicates potential integration / configuration errors or SDK issues.
  • ERROR: Indicates important integration errors or non-recoverable SDK issues.
  • DEBUG: Debug logs, used by the developers to debug more complex issues.

Once the flag is active, it logs each API call made and the data passed. The log created by this flag is minimal.

Note: DO NOT activate the Debug flag in a production environment.

Swift Example

Sample SDK Initialization Code

NielsenInit.swift

class NielsenInit: NSObject {
    class func createNielsenAppApi(delegate: NielsenAppApiDelegate) -> NielsenAppApi?{
    let appInformation:[String: String] = [
           "appid": "PE392366B-F2C1-4BC4-AB62-A7DAFDCXXXX",
           "nol_devDebug": "DEBUG"
        ]
        return NielsenAppApi(appInfo:appInformation, delegate:delegate)}}


ViewController.swift

class ViewController: UIViewController, NielsenAppApiDelegate, AVPictureInPictureControllerDelegate, CLLocationManagerDelegate  {

    let avPlayerViewController = AVPlayerViewController()
    var avPlayer:AVPlayer?
    var nielsenAppApi: NielsenAppApi!

  override func viewDidLoad() {
        super.viewDidLoad()
        self.nielsenAppApi = NielsenInit.createNielsenAppApi(delegate: self)
        NSLog("Nielsen SDK initialized")
}}

Objective C

Sample SDK Initialization Code

Initialize the Nielsen App object within the viewDidLoad view controller delegate method using initWithAppInfo:delegate:

If App SDK is initialized using init or new methods, it will ignore the API calls resulting in no measurement. The SDK will not return any errors.

#import "NlsAppApiFactory.h"
#import <NielsenAppApi/NielsenAppApi.h>

@implementation NlsAppApiFactory
+ (NielsenAppApi *)createNielsenAppApiWithDelegate:(id<NielsenAppApiDelegate>)delegate;
{
    NSDictionary *appInformation = @{
                                     @"appid": "PE392366B-F2C1-4BC4-AB62-A7DAFDC51XXX",
                                     @"nol_devDebug": @"DEBUG"
                                     };
    return [[NielsenAppApi alloc] initWithAppInfo:appInformation delegate:delegate];
}
@end


The following would be the NlsAppApiFactory.h file:

#import <Foundation/Foundation.h>

@class NielsenAppApi;
@protocol NielsenAppApiDeligate;
@interface NlsAppApiFactory : NSObject
+ (NielsenAppAPI *) createNielsenAppApiWithDelegate:(id<NielsenAppApiDelegate>)delegate;
@end
}}


The following might be in the Viewcontroller.m

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //Setting background image
    UIImage *backgroundImage = [UIImage imageNamed:@"new_ios_bg.png"];
    UIImageView *backgroundImageView=[[UIImageView alloc]initWithFrame:self.view.frame];
    backgroundImageView.image=backgroundImage;
    [self.view insertSubview:backgroundImageView atIndex:0];
    
    //Mark: In NielsenInit class we are initialising the Nielsen SDK.
    
    //Getting the instance of Nielsen SDK
    nielsenApi = [NielsenInit createNielsenAppApiWithDelegate:nil];
}


Initializing Viewability and Audibility Measurement

If your Nielsen integration will be enabled for viewability/audibility measurement, your app should call trackViewability after initializing the SDK (previous paragraphs).

Viewability metrics allow AppSDK to track the visibility of the player and collect information about how much of the player container is visible to the end user during playback. Audibility metrics report on the device volume level.

The viewability pings will be fired following the same rules as measurement pings. Viewability pings will be POST requests, not GET requests like other data pings. POST body for viewability requests will contain the key-value pairs in JSON format. The key parameters in the URL schemes are invs, inau, inss, invp and ines which will contain the collected viewability data. This data will be formatted according to the specific rules so that downstream it will be possible to match measurement and viewability data for a session.

Audibility metrics will capture the volume level as well as mute/unmute state of the device during playback.

Calling trackViewability for player view

Input Parameters

Parameter Description
data NSDictionary object with the following objects and keys:
viewTag (mandatory) value of NSNumber type, unique identifier (tag) for the target view object. This tag can be assigned for the player view either programmatically or in the storyboard/xib.
viewContainer (mandatory) pointer to the parent view object. It is needed to identify the concrete scene in the applications which support multiple scenes. This parameter can not be nil.
friendlyObstructions (nullable) an array of tags of the views which should be ignored during the intersection ratio calculation. Those are views like loading activity indicator, player controls, view with a watermark, etc. which are displayed in front of the target view, but should not reduce the viewability intersection ratio. The tags of such should be wrapped into the NSNumber objects before adding into the array. This parameter is nullable, empty array is also accepted.


Objective C

NSString *targetViewTag = targetView.tag;
NSString *controlsViewTag = controlsViewTag.tag;
NSString *activityIndicatorViewTag = activityIndicatorView.tag;
NSDictionary *viewabilityData = @{@"viewTag": targetViewTag,
                                  @"viewContainer": targetView.window,
                                  @"friendlyObstructions": @[controlsViewTag, activityIndicatorViewTag]};
[sdkInstance trackViewability:viewabilityData];


Swift

let targetViewTag = targetView.tag
let controlsViewTag = controlsViewTag.tag
let activityIndicatorViewTag = activityIndicatorView.tag
let viewabilityData: [String:Any] = ["viewTag": "\(targetViewTag)",
                                     "viewContainer": targetView.window!,
                                     "friendlyObstructions": ["\(controlsViewTag)", "\(activityIndicatorViewTag)"]]
sdkInstance.trackViewability(viewabilityData)


PlayerView FirendlyView(Timer & Slider).png

Data Collected

Parameter Description
Measured Value Value is different for different request parameters:
invs Intersection ratio for the target view in percent (from 0 to 100). Default threshold for this value is 5. Example: [50,1,1528457356,10]
inau Volume level on the device in percent (from 0 to 100), where 0 - mute, 100 - max volume level. Default threshold for this value is 1. Example: [30,1,1528457356,10]
inss Device screen size as "WxH", where W - is width in pixels, H - is height in pixels. Example: ["1024x768",1,1528457356,10]
invp Current window size. This is different than the device screen size in a multiple scene mode or on a desktop. Format is "WxH", where W - is width in pixels, H - is height in pixels. Example: ["800x600",1,1528457356,10]
ines Player view size as "WxH", where W - is width in pixels, H - is height in pixels. Example: ["300x200",1,1528457356,10]
Start offset Value contains the first playhead or the first id3 offset with non-null CID after start, flush or resume. Example playhead: [50,1,1528457356,10]. Example id3 offset: [50,70100,1528457356,10]
Start timestamp Timestamp value when the time period related to this time series item was started. Example: [50,1,1528457356,10]
Duration Duration value is calculated as a difference between the last playhead and the first playhead for the current time series item. Example: [50,1,1528457356,10]

Configure 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 Nielsen Key names (e.g. appid, program) 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.


Create channelName Metadata

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

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

Create Content Metadata

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

program and title metadata values should be passed to SDK as UTF-8 strings.

Key Description Values Required
clientid

parent ID – value is automatically populated through provided App ID.
In order to override the brand configured to the App ID, pass parent
value here and the sub-brand ID associated to that brand in the subbrand
key (e.g. multiple brands in App)

Nielsen provided

subbrand sub-brand ID – value is automatically populated through provided

App ID. In order to override the sub-brand configured to the App ID, value can
be passed here (e.g. multiple sub-brands in App)

Nielsen provided

type type of asset "content"
assetid unique ID assigned to asset custom
(no Special Characters). The Content ID should be populated here which should correspond to the same value in the post transmission logs.
program name of program custom
title episode name custom
length length of content in seconds seconds (86400 for live stream)
segB custom segment B. Custom segments can be used to aggregate content however you choose. Some examples include genre, category, or platform. custom
segC For VOD: Populate TVContent ID, For livestream: leave blank custom Required for VOD only
isfullepisode full episode flag
  • 'y', 'yes', or 'lf' – full episode
  • 'n', 'no', or 'sf' – non full episode

Note: For livestream content with Dynamic Ad Insertion (DAI), the isfullepisode value should be set to 'y'.

adloadtype type of Ad load:
  • 1) Linear – matches TV Ad load. Content with linear Ad Load is not eligible for DCR measurement and will not be included in DCR reporting.
  • 2) Dynamic – Dynamic Ad Insertion (DAI)
  • "1" – content with linear Ads. Note: Content with linear Ad load is not included in DCR measurement.
  • "2" – content with dynamic Ads

Metadata Example

Swift

let contentMetadata = [
    "type": "content",
    "assetid": "C77664",
    "title": "Program S2, E3",
    "isfullepisode": "y",
    "program": "Program Name",
    "length": "3600",
    "adloadtype": "2",
    "segB": "CustomSegmentValueB", //optional
    "segC": "CustomSegmentValueC", //optional
];


Objective-C

 
NSDictionary * contentMetadata = @ {
    @ "type": @ "content",
    @ "assetid": @ "C77664",
    @ "title": @ "S2,E3",
    @ "isfullepisode": @ "y",  
    @ "program": @ "Program Name",
    @ "length": @ "3600",
    @ "adloadtype": @ "2",
    @ "segB": @ "CustomSegmentValueB", //optional
    @ "segC": @ "CustomSegmentValueC", //optional
}

Ad Metadata

The Ad Metadata (if applicable) should be passed for each individual ad.

Keys Description Values Required
type type of Ad 'preroll', 'midroll', 'postroll'
'ad' - If specific type can not be identified.
assetid unique ID assigned to Ad custom
(no Special Characters)

Example Ad Object

// create Ad object
"ad": {
  "type": "preroll",
  "assetid": "AD-ID123"
}

Life cycle of SDK instance

The 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. API calls "play" and "loadMetadata" move the SDK instance into this state. In this state, the SDK instance will be able to process the API calls (see below)
  4. 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.
    1. Initialization fails
    2. appDisableApi is called
@property (assign) BOOL appDisableApi;

APP SDK Error & Event Codes

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

Configure API Calls

Sample API Sequence

A Sample API sequence could follow this flow:

Type Sample code Description
Start of stream nielsenMeter.play() // Call at start of each new stream
nielsenMeter.loadMetadata(contentMetadata) // MetadataObject contains the JSON metadata
for the content being played
Content nielsenMeter.playheadPosition(pos); // playheadPosition is position of the playhead
while the content is being played
End of Stream nielsenMeter.end() // Content playback is completed.

SDK Events

Event Parameter Description
'play' Call at start of each new stream
'loadMetadata' content/ad metadata object Needs to be called at the beginning of each asset
'playheadPosition' playhead position as integer

VOD: current position in seconds
Live: current UNIX timestamp (seconds since Jan-1-1970 UTC)
Note: 'PlayheadPosition' has to be called every second

Pass playhead position every second during playback

'stop' playhead position Call during any interruption to content or Ad playback and at the end of each Ad.
'end' playhead position in seconds Call when the current video asset completes playback and pass the playhead position.

Example: At the end of the content stream, if the user switches to another piece of content, when the browser is refreshed or closed.

Note: For livestream, send the UNIX timestamp, for VOD send the time in seconds as integer. The final playhead position must be sent for the current asset being played before calling stop, end or loadmetadata,.

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 Idle 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 an event to occur.
  3. Processing state – The SDK instance is processing playing information. The 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 is active. If a LIVE event, use the current UNIX timestamp (seconds since Jan-1-1970 UTC).
    2. stop – Call this API when the content or Ad playback is interrupted and at the end of each Ad.
    3. end – Call when content completes. When called, the SDK instance exits from Processing state.
  4. Disabled state – The SDK instance is disabled and is not processing playing information.
    1. appDisableApi is set to true

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

API Call Sequence

Use Case 1: Content has no Advertisements

Call play() at start of stream

Call loadMetadata() with JSON metadata for content as below.

{
  "type": "content",
  "assetid": "vid345-67483",
  "program": "ProgramName",
  "title": "Program S3, EP1",
  "length": "3600",
  ...
}

Call playheadPosition() every one second until a pause / stop. Use the sample API sequence below as a reference to identify the specific events that need to be called during content playback without ads.

Type Sample code Description
Start of stream mAppSdk.play(); // Call at start of each new stream
mAppSdk.loadMetadata(contentMetaDataObject); // contentMetadataObject contains the JSON metadata for the content being played
Content mAppSdk.setPlayheadPosition(playheadPosition); // position is position of the playhead while the content is being played
Interruption mAppSdk.stop(); // call stop when content playback is interrupted
Resume Content mAppSdk.loadMetadata(contentMetaDataObject); // Call loadMetadata and pass content metadata object when content resumes
mAppSdk.setPlayheadPosition(playheadPosition); // continue pasing playhead position every second starting from position where content is resumed
End of Stream mAppSdk.end(); // Content playback is completed.

Use Case 2: Content has Advertisements

Call play() at start of stream

Call loadMetadata() with JSON metadata for ad as below.

{
   "type": "preroll",
   "assetid": "ad123"
}

Note: In case the individual ad details are not available, send ad pod (presence) details through the loadMetadata and playhead position through playheadPosition.

Call playheadPosition() every one second until a pause / stop / another loadMetadata() is called. Playhead should be passed for the entire duration of ad pod, if the ad pod details are passed as part of loadMetadata().

The sample API sequence can be used as a reference to identify the specific events that need to be called during content and ad playback.

Type Sample code Description
Start of stream mAppSdk.play(); // stream starts
mAppSdk.loadMetadata(contentMetaDataObject); // contentMetadataObject contains the JSON metadata for the content being played
Preroll mAppSdk.loadMetadata(prerollMetadataObject); // prerollMetadataObject contains the JSON metadata for the preroll ad
mAppSdk.playheadPosition(playheadPosition); // position is position of the playhead while the preroll ad is being played
mAppSdk.stop(); // Call stop after preroll occurs
Content mAppSdk.loadMetadata(contentMetaDataObject); // contentMetadataObject contains the JSON metadata for the content being played
mAppSdk.playheadPosition(playheadPosition); // position is position of the playhead while the content is being played
Midroll mAppSdk.loadMetadata(midrollMetaDataObject); // midrollMetadataObject contains the JSON metadata for the midroll ad
mAppSdk.playheadPosition(playheadPosition); // position is position of the playhead while the midroll ad is being played
mAppSdk.stop(); // Call stop after midroll occurs
Content Resumes mAppSdk.loadMetadata(contentMetaDataObject); // contentMetadataObject contains the JSON metadata for the content being played
mAppSdk.playheadPosition(playheadPosition); // position is position of the playhead while the content is being played
End of Stream mAppSdk.end(); // Call end() at the end of content
Postroll mAppSdk.loadMetadata(postrollMetaDataObject); // postrollMetadataObject contains the JSON metadata for the postroll ad
mAppSdk.playheadPosition(playheadPosition); // position is position of the playhead while the postroll ad is being played
mAppSdk.stop(); // Call stop after postroll occurs

Note: Each Ad playhead should begin from 0 at ad start. When content has resumed following an ad break, playhead position must continue from where previous content segment was left off.

Sequence of Calls

play

Call play at the start of each new stream. If changing videos or watching a new video, call play() each time.

Objective C

   [nielsenAppApi play:()];

Swift

nielsenAppApi?.play();

loadMetadata

Objective C

[nielsenApi loadMetadata:(contentMetadata)];

Swift

self.nielsenAppApi?.loadMetadata(contentMetadata)

playheadPosition

Objective C

-(void) setPlayHeadPosition {
    
    //Setting play head position
    CMTime timeInterval = CMTimeMakeWithSeconds(1, 1);
    [player addPeriodicTimeObserverForInterval:(timeInterval) queue:dispatch_get_main_queue() usingBlock:^(CMTime time){
        NSTimeInterval seconds = CMTimeGetSeconds(time);
        NSInteger intSec = seconds;
        
        //Sending data dictionary to SDK with updated playHead position.
        [nielsenApi playheadPosition:(intSec)];
    }];
}

Swift

        //Monitor the Playhead position of the AVPlayer
        let timeInterval: CMTime = CMTimeMakeWithSeconds(1.0,10)
        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);
            }
        }
    }

stop

Objective C

[nielsenApi stop];

Swift

nielsenApi.stop()

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

Objective C

[nielsenApi end];

Swift

nielsenApi.end()

Handling Foreground and Background states

For iOS, background/foreground detection is handled by the app lifecylce APIs which are provided by Apple:

Foreground/Background state measurement is a requirement of Nielsen AppSDK implementation which is especially crucial for static measurement.

Interruptions during playback

As part of integrating Nielsen App SDK with the player application, the Audio / Video app developer needs to handle the following possible interruption scenarios:

  • Pause / Play
  • Network Loss (Wi-Fi / Airplane / Cellular)
  • Call Interrupt (SIM or Third party Skype / Hangout call)
  • Alarm Interrupt
  • Content Buffering
  • Device Lock / Unlock
  • App going in the Background/Foreground
  • Channel / Station Change Scenario
  • Unplugging of headphone

In case of encountering one of the above interruptions, the player application needs to

  • Call stop immediately (except when content is buffering) and withhold sending playhead position.
  • Start sending API calls – 'loadMetadata' and 'playheadPosition' for the new viewing session, once the playback resumes.

Please see the Interruption Scenarios Page for more details

Using the NielsenAppSDKJSHandler

There could be a scenario in which a browser page, that is already tagged with the Nielsen BSDK, needs to be loaded via a webview. In this situation it is recommended to use the NielsenAppSDKJSHandler which will allow communication between the AppSDK and the BSDK.

This feature is supported in versions 7.2 and above.

Implementation

  • Make sure you have the latest NielsenAppApi.framework from Nielsen containing the NielsenAppSDKJSHandler class.
  • Add NielsenAppSDKJSHandler instance as web view message handler object conforming to WKScriptMessageHandler protocol with name: "NielsenSDKMsg".


Objective-C:

self.jsAppSDK = [[NielsenAppSDKJSHandler alloc] init];
[self.webView.configuration.userContentController addScriptMessageHandler:self.jsAppSDK name:@"NielsenSDKMsg"];


Swift:

self.jsAppSDK=NielsenAppSDKJSHandler(apiType: "ggPM")
if let jsAppSDK = self.jsAppSDK{
   self.webView?.configuration.userContentController.add(jsAppSDK, name: "NielsenSDKMsg")


This will enable listening to BSDK api calls within the APPSDK. Please make sure your Technical Account Manager is aware that you wish to implement this method so a configuration file can be modified on the Nielsen servers; however, there are no changes required to the Browser page.

Example:

The below is an example of opening a webview with the NielsenApp[SDKJSHandler using Swift 5.0

  let jsFunctionNativeMessage = "NielsenSDKMsg"
  var jsAppSDK: NielsenAppSDKJSHandler?
    
    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "https://nielsen.com/index.htm")!
        self.jsAppSDK=NielsenAppSDKJSHandler(apiType: "ggPM")
        if let jsAppSDK = self.jsAppSDK{
            self.webView?.configuration.userContentController.add(jsAppSDK, name: "NielsenSDKMsg")
            webView.load(URLRequest(url: url))
            webView.allowsBackForwardNavigationGestures = true
        }
}
    deinit {
        if let webView = self.webView {
            webView.configuration.userContentController.removeScriptMessageHandler(forName: jsFunctionNativeMessage)
        }
        self.jsAppSDK = nil
        if let webView = self.webView {
            webView.removeFromSuperview()
        }
        self.webView = nil
    }
}


Please note: The page you load into the webview cannot have mixed protocol content. For example, if your page is https:// you cannot have any images on the page as http:// or you will encounter errors.

Pre-Certification Checklists

After the application is ready to be sent for Nielsen Certification, please go through the Digital Pre-Certification Checklist App SDK and ensure the app behaves as expected, before submitting to Nielsen.

Privacy and Opt-Out

There are currently 3 flavors of the Nielsen SDK:

  1. Global iOS SDK Opt-out - managed by AppTracking or Limit Ad Tracking setting on device (preferred approach).
  2. Global iOS SDK No Ad Framework Optout - Direct call to SDK. Can be used without the Ad Framework
  3. Global iOS SDK No ID Optout - Direct call to SDK. Should be used for Kids Category.

Global iOS SDK Opt-out

OS-level Opt-out method available on Nielsen iOS

The Nielsen SDK automatically leverages the iOS's Limit Ad Tracking or AppTracking setting.

  • If the User's device is running < iOS 13.x, the Nielsen SDK will check the status of Limit Ad Tracking.
  • iOS14 modifies the way Apple manages the collection of a User's Opt-In status through AppTracking. Starting with Version 8.x+, the Nielsen App SDK will check the iOS version during initialization. If the device is running iOS12 or iOS13, the Limit Ad Tracking setting is requested. If iOS14.x +, then AppTracking is utilized.

Webview Element

It is a requirement to display a WebView element whose loadUrl is set to the value obtained from optOutURL. If using the Global iOS SDK, this optOutURL informs the user how to deactivate/activate “App Tracking/Limit Ad Tracking”.

In addition, The following text must be included in your app store description.

"Please note: This app features Nielsen’s proprietary measurement software which contributes to market research, like Nielsen’s Digital Content Ratings. Please see https://www.nielsen.com/th/en/legal/privacy-statement/digital-measurement/ for more information"

Global iOS SDK No Ad Framework Optout

The User Choice method can be used without the Ad Framework, or in situations where the publisher does not wish to use the App Tracking Transparency Framework. As this flavor of the Nielsen SDK does not use the Ad Framework, so it is necessary to display an Optout Page to the userand capture their selection.

Similar to the Global iOS SDK Flavor, it is a requirement to display a WebView element whose loadUrl is set to the value obtained from optOutURL. This is a special URL that indicates Opt-in, or Opt-out and close the WebView.

This opt-out method works as follows:

  • Get the Nielsen opt-out URL via optOutURL
  • Display a WebView element whose loadUrl is set to the value obtained from optOutURL
  • Detect if the WebView URL changes to a special URL that indicates Opt-in, or Opt-out and close the WebView
    • Opt-out if the WebView URL = nielsenappsdk://1
    • Opt-in if the WebView URL = nielsenappsdk://0
  • Pass the detected URL to the userOptOut function
    • Example:
      NielsenAppApi?.userOptOut("nielsenappsdk://1"); // User opt-out
      

Global iOS SDK No ID Optout (Kids Category)

If you are building an app that will be listed in the Kids Category:

  1. Ensure that you are using the NoID version of the Nielsen SDK Framework.
  2. Immediately following the initialization of the Nielsen SDK ensure you call the userOptOut API with Opt out selection:
NielsenAppApi?.userOptOut("nielsenappsdk://1"); // User opt-out

Opt-out example code

Swift
import UIKit
import WebKit
import NielsenAppApi

class OptOutVC: UIViewController, NielsenAppApiDelegate, WKNavigationDelegate {
    var nielsenApi : NielsenAppApi!
    var webView: WKWebView!
   
    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if let appApi = self.nielsenApi {
            //Getting the optPut URL from SDK
            if let url = URL(string: appApi.optOutURL) {
                webView.load(URLRequest(url: url))
                webView.allowsBackForwardNavigationGestures = true
            }}}

        func closeOptOutView() {
            self.dismiss(animated: true, completion: nil)
        }
  
// Uncomment below code if you are using the Global iOS SDK No Ad Framework Flavor.  This will receive the user's selection
// From the custom User_Choice opt out page.  Only required for non-ad framework or no-id builds
// of the Nielsen SDK
/*  
        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: 
@escaping (WKNavigationActionPolicy) -> Void) {
            print(navigationAction.request.url?.absoluteString as Any) //For debugging to check what is being passed from webpage.
            if navigationAction.request.url?.absoluteString == "nielsen://close" {
                closeOptOutView()
                decisionHandler(.cancel)
            } else {
                if let url = navigationAction.request.url?.absoluteString, url.hasPrefix("nielsen") {
                    nielsenApi?.userOptOut(url). //either nielsenappsdk://1 or nielsenappsdk://0
                    decisionHandler(.cancel)
                } else {
                    if navigationAction.navigationType == .linkActivated {
                        if let url = navigationAction.request.url?.absoluteString, url.hasSuffix("#") {
                            decisionHandler(.allow)
                        } else {
                            decisionHandler(.cancel)
                            webView.load(navigationAction.request)
                        }
                    } else {
                        decisionHandler(.allow)
                    }}}}
  */
}
Objective-C
#import "OptOutVC.h"
#import "NielsenInit.h"
#import <NielsenAppApi/NielsenAppApi.h>

@interface OptOutVC ()

@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end

@implementation OptOutVC

- (void)viewDidLoad {
    [super viewDidLoad];

- (void)viewDidLoad {
    [super viewDidLoad];
    //Getting the optPut URL from eventTracker
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL
 URLWithString:self.nielsenApi.optOutURL]]];
}

//Uncomment below code if you are using the Global iOS SDK No Ad Framework Flavor.
// From the custom User_Choice opt out page.  Only required for non-ad framework or no-id builds
// of the Nielsen SDK
/*     
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
 decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    if ([navigationAction.request.URL.absoluteString isEqualToString:kNielsenWebClose])
    {   [self performSelector:@selector(closeOptOutView) withObject:nil afterDelay:0];
        decisionHandler(WKNavigationActionPolicyCancel); 
     } else {
        if ([navigationAction.request.URL.absoluteString hasPrefix:@"nielsen"])
        {[self.nielsenAppApi userOptOut:navigationAction.request.URL.absoluteString];
            decisionHandler(WKNavigationActionPolicyCancel); 
        } else {
            if (navigationAction.navigationType == WKNavigationTypeLinkActivated) 
            { if ([navigationAction.request.URL.absoluteString hasSuffix:@"#"]) 
                      {decisionHandler(WKNavigationActionPolicyAllow);
                } else {
                    decisionHandler(WKNavigationActionPolicyCancel);
                    [webView loadRequest:[NSURLRequest requestWithURL:navigationAction.request.URL]];
                }} else {
                 decisionHandler(WKNavigationActionPolicyAllow);
            }}}
*/
}

Retrieve current Opt-Out preference

Whether the user is opted out via OS-level Opt-out or via User Choice Opt-out, the current Opt-Out status as detected by the SDK is available via the optOutStatus property in the Nielsen SDK API

@property (readonly) BOOL optOutStatus

AirPlay

To implement OTT measurement, report OTT changes to the SDK using public API interface: updateOTT

In order to detect AirPlay and mirroring changes we use AVAudioSessionPortDescription properties that are different on different iOS versions. We found that on iOS versions 8 - 10 AVAudioSessionPortDescription has the following values:
AirPlay: type = AirPlay; name = Apple TV 4K; UID = DC:56:E7:53:72:85-airplay
Mirroring: type = AirPlay; name = Apple TV 4K; UID = DC:56:E7:53:72:85-screen

For iOS 11+ some parameters like name and UID have different values:
AirPlay: type = AirPlay; name = AirPlay; UID = 0eb63aae-5915-45f1-b0f7-0102a0e50d53
Mirroring: type = AirPlay; name = Apple TV 4K; UID = 4335E8A9-1C0A-4251-9000-28CA5FA2F3CF-192731714653291-screen

The following code snipped is suggested for AirPlay / mirroring detection on iOS devices.

Swift

nielsenSdk.updateOTT(currentStatus)

Subscribe to AVAudioSessionRouteChangeNotification

NotificationCenter.default.addObserver(self, selector: #selector(handleRouteChanged(_:)), name: NSNotification.Name.AVAudioSessionRouteChange, object: nil)

Handle AVAudioSessionRouteChangeNotification and prepare OTT dictionary:

func handleRouteChanged(_ notification: Notification) {
var currentStatus: [String: String] = ["ottStatus": "0"]

let session = AVAudioSession.sharedInstance()
let currentRoute = session.currentRoute
for outputPort in currentRoute.outputs {
if outputPort.portType == AVAudioSessionPortAirPlay {
currentStatus["ottStatus"] = "1"
currentStatus["ottDeviceModel"] = outputPort.portName
currentStatus["ottDeviceID"] = outputPort.uid

if outputPort.portName == "AirPlay" {
currentStatus["ottDevice"] = "airplay"
currentStatus["ottType"] = "airplay"
}
else {
if outputPort.portName.contains("Apple TV") {
currentStatus["ottDevice"] = "appleTV"
}
else {
currentStatus["ottDevice"] = "other"
}

if outputPort.uid.hasSuffix("airplay") {
currentStatus["ottType"] = "airplay"
}
else if outputPort.uid.hasSuffix("screen") {
currentStatus["ottType"] = "mirroring"
}
else {
currentStatus["ottType"] = "other"
}
}
}
}

// report OTT status update to Nielsen SDK
self.reportOTTUpdate(currentStatus)
}

Report OTT update to the Nielsen SDK

func reportOTTUpdate(_ ottDict: [String: String]) {
if let nielsenSdk = self.nielsenAppApi {
nielsenSdk.updateOTT(currentStatus)
}
}

Objective C

 (void)updateOTT:(id)ottInfo;

Subscribe to AVAudioSessionRouteChangeNotification

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRouteChanged:) name:AVAudioSessionRouteChangeNotification object:nil];

Handle AVAudioSessionRouteChangeNotification and prepare OTT dictionary:

- (void)handleRouteChanged:(NSNotification *)notification
{
NSMutableDictionary *ottDict = [NSMutableDictionary dictionaryWithDictionary: @{@"ottStatus": @"0"}];

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
AVAudioSessionRouteDescription *currentRoute = audioSession.currentRoute;
for (AVAudioSessionPortDescription *outputPort in currentRoute.outputs) {
if ([outputPort.portType isEqualToString:AVAudioSessionPortAirPlay]) {
ottDict[@"ottStatus"] = @"1";
ottDict[@"ottDeviceModel"] = outputPort.portName;
ottDict[@"ottDeviceID"] = outputPort.UID;

if ([outputPort.portName isEqualToString:@"AirPlay"]) {
ottDict[@"ottDevice"] = @"airplay";
ottDict[@"ottType"] = @"airplay";
}
else {
if ([outputPort.portName containsString:@"Apple TV"]) {
ottDict[@"ottDevice"] = @"appleTV";
}
else {
ottDict[@"ottDevice"] = @"other";
}

if ([outputPort.UID hasSuffix:@"airplay"]) {
ottDict[@"ottType"] = @"airplay";
}
else if ([outputPort.UID hasSuffix:@"screen"]) {
ottDict[@"ottType"] = @"mirroring";
}
else {
ottDict[@"ottType"] = @"other";
}
}
}
}

// report OTT status update to Nielsen SDK
[self reportOTTWithDict:ottDict];
}

Report OTT update to the Nielsen SDK

- (void)reportOTTWithDict:(NSDictionary *)ottDict
{
[self.nielsenSDK updateOTT:ottDict];
}


Going Live

Following Nielsen testing, you will need to:

  1. Disable Debug Logging: Disable logging by deleting {nol_devDebug: 'DEBUG'} from initialization call.
  2. Notify Nielsen: Once you are ready to go live, let us know so we can enable you for reporting. We will not be able to collect or report data prior to receiving notification from you.

Removing Simulators (Dynamic Framework Only)

Simulator slices are needed to let clients build and debug their app on the simulators, but they should be removed before sending the app to the AppStore. Here is an example Shell script that could be added as a Run Script phase in the application.


APP_PATH="${TARGET_BUILD_DIR}/${WRAPPER_NAME}"

# This script loops through the frameworks embedded in the application and
# removes unused architectures.
find "$APP_PATH" -name '*.framework' -type d | while read -r FRAMEWORK
do
FRAMEWORK_EXECUTABLE_NAME=$(defaults read "$FRAMEWORK/Info.plist" CFBundleExecutable)
FRAMEWORK_EXECUTABLE_PATH="$FRAMEWORK/$FRAMEWORK_EXECUTABLE_NAME"
echo "Executable is $FRAMEWORK_EXECUTABLE_PATH"

EXTRACTED_ARCHS=()

for ARCH in $ARCHS
do
echo "Extracting $ARCH from $FRAMEWORK_EXECUTABLE_NAME"
lipo -extract "$ARCH" "$FRAMEWORK_EXECUTABLE_PATH" -o "$FRAMEWORK_EXECUTABLE_PATH-$ARCH"
EXTRACTED_ARCHS+=("$FRAMEWORK_EXECUTABLE_PATH-$ARCH")
done

echo "Merging extracted architectures: ${ARCHS}"
lipo -o "$FRAMEWORK_EXECUTABLE_PATH-merged" -create "${EXTRACTED_ARCHS[@]}"
rm "${EXTRACTED_ARCHS[@]}"

echo "Replacing original executable with thinned version"
rm "$FRAMEWORK_EXECUTABLE_PATH"
mv "$FRAMEWORK_EXECUTABLE_PATH-merged" "$FRAMEWORK_EXECUTABLE_PATH"

done

Sample Applications

The below sample applications have been designed to show the Simplified API's functionality and are broken into two distinct categories:

  • Advanced - Nielsen Simplified API integrated into a custom video player.