DCR Video iOS SDK: Difference between revisions

From Engineering Client Portal

No edit summary
No edit summary
Line 1: Line 1:
{{Breadcrumb|}} {{Breadcrumb|Digital}} {{Breadcrumb|DCR & DTVR}}  {{CurrentBreadcrumb}}
{{Breadcrumb|}} {{Breadcrumb|Digital}} {{Breadcrumb|DCR & DTVR}}  {{CurrentBreadcrumb}}
[[Category:Digital]]
[[Category:Digital]]
__TOC__


== Overview ==
== Overview ==
Line 8: Line 10:


== Prerequisites ==
== Prerequisites ==
To start using the App SDK, the following items are required:
Before you start the integration, you will need:
{| class="wikitable"
{| class="wikitable"
|-
|-
Line 15: Line 17:
! Source
! Source
|-
|-
  || '''App ID (appid)''' || Unique ID assigned to the player/site and configured by product. || Contact Nielsen
  || '''App ID (appid)''' || Unique ID assigned to the player/site and configured by product. || Provided by Nielsen
|-
|| '''sfcode''' || Environment that the SDK must point to || Contact Nielsen
|-
|-
  || '''Nielsen SDK''' || Includes SDK frameworks and '''sample implementation'''; ''See [[iOS SDK Release Notes]]'' || [[Special:Downloads|Download]]
  || '''Nielsen SDK''' || Includes SDK frameworks and '''sample implementation'''; ''See [[iOS SDK Release Notes]]'' || [[Special:Downloads|Download]]
|}
|}


If you do not have any of these pre-requisites or if you have any questions, please contact our SDK sales support team.
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.
___TOC___


==  Implementation ==
==  Implementation ==
Line 74: Line 73:


The following table contains the list of arguments that can be passed via the AppInfo JSON schema.
The following table contains the list of arguments that can be passed via the AppInfo JSON schema.
* The appid is provided by the Nielsen Technical Account Manager (TAM). The appid is a GUID data type and is specific to the application.
{| class="wikitable"
{| class="wikitable"
|-
|-
! Parameter / Argument !! Description !! Source !! Required? !! Example
! Parameter / Argument !! Description !! Source !! Required? !! Example
|-
|-
| appid || Unique id for the application assigned by Nielsen. It is GUID data type.|| Nielsen-specified || Yes || PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
| 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
|-
| appname || Name of the application || Client-defined || Optional; automatically detected in SDK 6.0.0.4 and above || Nielsen Sample App
|-
| sfcode || Nielsen collection facility to which the SDK should connect.
'''DTVR'''
* "us"
'''DCR'''
* "dcr"
|| Nielsen-specified || Yes || dcr
|-
|-
| nol_devDebug || Enables Nielsen console logging. Only required for testing
| nol_devDebug || Enables Nielsen console logging. Only required for testing
Line 108: Line 96:


=== Sample SDK Initialization Code ===
=== Sample SDK Initialization Code ===
{{ExampleCode|
 
|Swift  =  
====Swift 4.0 Example:====
Swift 4.0 Example:
<code>NielsenInit.swift</code>
<code>NielsenInit.swift</code>
<syntaxhighlight lang="swift">
<syntaxhighlight lang="swift">
Line 121: Line 108:
         let appInformation:[String: String] = [
         let appInformation:[String: String] = [
             "appid": "PDA7D5EE6-B1B8-4123-9277-2A788XXXXXXX",
             "appid": "PDA7D5EE6-B1B8-4123-9277-2A788XXXXXXX",
            "sfcode": "dcr",
             "nol_devDebug": "DEBUG"
             "nol_devDebug": "DEBUG"
         ]       
         ]       
Line 129: Line 115:
</syntaxhighlight>
</syntaxhighlight>


Sample code using AVPlayer.
===Sample code using AVPlayer===
<code>ViewController.swift</code>
<code>ViewController.swift</code>


Line 146: Line 132:
   }
   }
</syntaxhighlight>
</syntaxhighlight>
|Objective C =  
 
===Objective C ====  
Initialize the Nielsen App object within the viewDidLoad view controller delegate method using initWithAppInfo:delegate:
Initialize the Nielsen App object within the viewDidLoad view controller delegate method using initWithAppInfo:delegate:
<blockquote>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.</blockquote>
<blockquote>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.</blockquote>
Line 160: Line 147:
      
      
     NSDictionary *appInformation = @{ @"appid": @"PDA7D5EE6-B1B8-4123-9277-2A788XXXXXXX",
     NSDictionary *appInformation = @{ @"appid": @"PDA7D5EE6-B1B8-4123-9277-2A788XXXXXXX",
                            @"appversion": @"1.0",
                             @"nol_devDebug": @"DEBUG" };
                            @"sfcode": @"dcr",
                             @"nol_devDebug": @"DEBUG", };
      
      
     return [[NielsenAppApi alloc] initWithAppInfo:appInformation delegate:delegate];
     return [[NielsenAppApi alloc] initWithAppInfo:appInformation delegate:delegate];
Line 184: Line 169:
@end
@end
</syntaxhighlight>
</syntaxhighlight>
Sample Code:
 
====Sample Code:====
<syntaxhighlight lang="objective-c">
<syntaxhighlight lang="objective-c">
@implementation ViewController
@implementation ViewController
Line 226: Line 212:
To view the Error and Event codes for iOS, please review the [[APP SDK Event Codes|App SDK Event Code]] Reference page.
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 ===
=== 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.
Line 234: Line 220:
* 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.
{{ExampleCode|
{{ExampleCode|
|Swift =  
|Swift =  
<syntaxhighlight lang="swift">
<syntaxhighlight lang="swift">
let channelInfo = [
    "channelName": "My Channel Name 1",
];


let contentMetadata = [
let contentMetadata = [
Line 250: Line 233:
     "program": "Program Name",
     "program": "Program Name",
     "length": "3600",
     "length": "3600",
     "airdate": "20171020 10:05:00",
     "airdate": "20200321 10:05:00",
     "adloadtype": "2",
     "adloadtype": "2",
     "segB": "CustomSegmentValueB", //optional
     "segB": "CustomSegmentValueB", //optional
     "segC": "CustomSegmentValueC", //optional
     "segC": "CustomSegmentValueC", //optional
    "crossId1": "Standard Episode ID", //optional
    "crossId2": "Content Originator" //optional
];
];
</syntaxhighlight>     
</syntaxhighlight>     
|Objective C = <syntaxhighlight lang="objective-c">  
|Objective C = <syntaxhighlight lang="objective-c">  
NSDictionary * channelInfo = @ {
    @ "channelName": @ "My Channel Name 1",
}
NSDictionary * contentMetadata = @ {
NSDictionary * contentMetadata = @ {
     @ "type": @ "content",
     @ "type": @ "content",
        @ "assetid": @ "C77664",
    @ "assetid": @ "C77664",
        @ "title": @ "S2,E3",
    @ "title": @ "S2,E3",
        @ "isfullepisode": @ "y",   
    @ "isfullepisode": @ "y",   
        @ "program": @ "Program Name",
    @ "program": @ "Program Name",
        @ "length": @ "3600",
    @ "length": @ "3600",
        @ "airdate": @ "20180120 10:00:00",
    @ "airdate": @ "20200321 10:05:00",
        @ "adloadtype": @ "2",
    @ "adloadtype": @ "2",
        @ "segB": @ "CustomSegmentValueB", //optional
    @ "segB": @ "CustomSegmentValueB", //optional
        @ "segC": @ "CustomSegmentValueC", //optional
    @ "segC": @ "CustomSegmentValueC", //optional
    @ "crossId1": @ "Standard Episode ID", //optional
    @ "crossId2": @ "Content Originator" //optional
}
}
</syntaxhighlight>
</syntaxhighlight>
}}
}}
 
<!--
=== Configure metadata ===  
=== 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.
Line 288: Line 271:
|-
|-
|}
|}
-->


=== Content metadata ===
=== Content Metadata ===
Content metadata should remain constant throughout the entirety of an episode/clip including when ads play.
Content metadata should remain constant throughout the entirety of an episode/clip including when ads play.
{{DCR Content Metadata}}
{{DCR Content Metadata}}


=== 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.
{| class="wikitable"
{| class="wikitable"
|-
|-
! Keys !! Description !! Values !! Required
! Keys !! Description !! Values !! Required
|-
|-
| type || ad vs content || <code>'ad'</code>|| ✓
| 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 || ✓
|}
|}
=== Example Ad Object ===
=== Example Ad Object ===
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
// create ad object
// create Ad object
"ad": {
"ad": {
   "type": "preroll",
   "type": "preroll",
Line 353: Line 338:
             [
             [
                 "type": "static",
                 "type": "static",
                 "section": "Sub Brand A",
                 "section": "Section Name",
                 "segA": "segmentA",
                 "segA": "segmentA",
                 "segB": "segmentB",
                 "segB": "segmentB",
Line 361: Line 346:


== Configure API Calls ==
== Configure API Calls ==
[[File:appsdkTimeline-DCR.png|icon|link=]]
<!--[[File:appsdkTimeline-DCR.png|icon|link=]]-->
=== Sample API Sequence ===
=== Sample API Sequence ===
A Sample API sequence could follow this flow:
A Sample API sequence could follow this flow:
Line 373: Line 358:
self.nielsenMeter .loadMetadata(self.data)</syntaxhighlight> || // Pass Static Metadata here if applicable
self.nielsenMeter .loadMetadata(self.data)</syntaxhighlight> || // Pass Static Metadata here if applicable
|-
|-
| rowspan="2" | Start of stream || <code>nielsenMeter.play(channelName)</code> || // channelName now automatically generated by Nielsen SDK
| 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
| <code>nielsenMeter.loadMetadata(contentMetadata)</code> || // MetadataObject contains the JSON metadata<br> for the content being played
Line 386: Line 371:
|-
|-
! Event !! Parameter !! Description
! 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
| 'loadMetadata' || content/ad metadata object || Needs to be called at the beginning of each asset
Line 396: Line 383:
Pass playhead position every second during playback
Pass playhead position every second during playback
|-
|-
| 'stop' || playhead position || Call when content or ads complete playing and pass playhead position
| '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/>
| 'end' || playhead position in seconds || Call when the current video asset completes playback and pass the playhead position. <br/>
Line 409: Line 396:
# '''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.
# '''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.
## <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).
## <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).
## <code>'''stop'''</code> – 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.  
## <code>'''end'''</code> – 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.  
# '''Disabled state''' – The SDK instance is disabled and is not processing playing information.  
## <code>'''appDisableApi'''</code> is set to <code>true</code>
## <code>'''appDisableApi'''</code> is set to <code>true</code>
Line 417: Line 404:


'''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.
'''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>'''play'''</code>, <code>'''loadMetadata''' </code> and  <code>'''playheadPosition'''</code> </blockquote>
* As soon as the playback resumes, call <code>'''loadMetadata''' </code> and  <code>'''playheadPosition'''</code> </blockquote>


=== API Call Sequence ===
=== API Call Sequence ===
==== Use Case 1: Content has no Advertisements ====
==== Use Case 1: Content has no Advertisements ====
Call [[play()]] with channelName JSON as below.
Call [[play()]] at start of stream
<syntaxhighlight lang="json">{
 
  "channelName": "TheMovieTitle"
}</syntaxhighlight>
Call [[loadMetadata()]] with JSON metadata for content as below.
Call [[loadMetadata()]] with JSON metadata for content as below.
<syntaxhighlight lang="json">{
<syntaxhighlight lang="json">{
Line 440: Line 425:
! Type !! Sample code !! Description
! Type !! Sample code !! Description
|-
|-
| rowspan="2" | Start of stream || <code>mAppSdk.play(channelName); </code> || // channelName now automatically generated by Nielsen SDK
| 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
|-
|-
| Content || <code>mAppSdk.playheadPosition(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
|-
|-
| rowspan="2" | Resume Content || <code>mAppSdk.loadMetadata(contentMetaDataObject);</code>  || // Call loadMetadata and pass content metadata object when content resumes
|-
|<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()]] with channelName JSON as below.
Call [[play()]] at start of stream
<syntaxhighlight lang="json">{
 
  "channelName": "TheMovieTitle"
}</syntaxhighlight>
Call [[loadMetadata()]] with JSON metadata for ad as below.
Call [[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 [[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>
Line 468: Line 457:
! Type !! Sample code !! Description
! Type !! Sample code !! Description
|-
|-
| rowspan="2" | Start of stream || <code>mAppSdk.play(channelName); </code> || // channelName now automatically generated by Nielsen SDK
| 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 478: Line 467:
| <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.playheadPosition(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
|-
|-
| <code>mAppSdk.stop();</code> || // Call stop after the content is paused (ad starts)
| rowspan="3" | Midroll || <code>mAppSdk.loadMetadata(midrollMetaDataObject);</code> || // midrollMetadataObject contains the JSON metadata for the midroll ad
|-
| rowspan="6" | Midroll || <code>mAppSdk.loadMetadata(midrollMetaDataObject);</code> || // midrollMetadataObject contains the JSON metadata for the midroll ad
|-
|-
| <code>mAppSdk.playheadPosition(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.playheadPosition(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.playheadPosition(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
|-
| <code>mAppSdk.stop();</code> || // Always call stop irrespective of postroll is followed or not
|-
|-
| 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 515: Line 494:
== Sequence of Calls ==
== Sequence of Calls ==
=== play ===
=== play ===
Use <code>play</code> to pass the channel descriptor information through channelName parameter when the user taps the '''Play''' button on the player.
Call <code>play</code> at the start of each new stream. If changing videos or watching a new video, call <code>play()</code> each time.  
{{ExampleCode|
{{ExampleCode|
|Objective C = <syntaxhighlight lang="objective-c">  [nielsenAppApi play:([NSDictionary *channel loadChannelInfo)];</syntaxhighlight>
|Objective C = <syntaxhighlight lang="objective-c">  [nielsenAppApi play:()];</syntaxhighlight>
|Swift = <syntaxhighlight lang="swift">nielsenAppApi?.play(channelInfo);</syntaxhighlight>
|Swift = <syntaxhighlight lang="swift">nielsenAppApi?.play();</syntaxhighlight>
}}
}}


Line 585: Line 564:
* Alarm Interrupt
* Alarm Interrupt
* Content Buffering
* Content Buffering
* Device Lock / Unlock (Video players only, not for Audio players)
* Device Lock / Unlock  
* App going in the Background/Foreground (Video players only, not for Audio players)
* App going in the Background/Foreground  
* Channel / Station Change Scenario
* Channel / Station Change Scenario
* Unplugging of headphone
* Unplugging of headphone
Line 593: Line 572:
* Start sending API calls – <code>'loadMetadata'</code> and <code>'playheadPosition'</code> for the new viewing session, once the playback resumes.
* Start sending API calls – <code>'loadMetadata'</code> and <code>'playheadPosition'</code> for the new viewing session, once the playback resumes.
Please see the [https://engineeringportal.nielsen.com/docs/Digital_Measurement_Interruption_Scenarios Interruption Scenarios Page] for more details
Please see the [https://engineeringportal.nielsen.com/docs/Digital_Measurement_Interruption_Scenarios 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.
<br>
'''This feature is supported in versions 7.2 and above.'''
<br>
=== 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".
<br>
'''Objective-C:'''
<syntaxhighlight lang=Objective-c>
self.jsAppSDK = [[NielsenAppSDKJSHandler alloc] init];
[self.webView.configuration.userContentController addScriptMessageHandler:self.jsAppSDK name:@"NielsenSDKMsg"];
</syntaxhighlight>
<br>
'''Swift:'''
<syntaxhighlight lang=Swift>
self.jsAppSDK=NielsenAppSDKJSHandler(apiType: "ggPM")
if let jsAppSDK = self.jsAppSDK{
  self.webView?.configuration.userContentController.add(jsAppSDK, name: "NielsenSDKMsg")
</syntaxhighlight>
<br>
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
<syntaxhighlight lang=java>
  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
    }
}
</syntaxhighlight>
<br>
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.
<br>


== Pre-Certification Checklists ==
== Pre-Certification Checklists ==
Line 743: Line 788:


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


# '''Debug Logging''': Disable logging by deleting <code>{nol_sdkDebug: 'DEBUG'}</code> from initialization call.
# '''Disable Debug Logging''': Disable logging by deleting <code>{nol_devDebug: 'DEBUG'}</code> from initialization call.
<br/>
# '''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.
'''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.


== Removing Simulators (Dynamic Framework Only)==
== Removing Simulators (Dynamic Framework Only)==
Line 794: Line 838:


* '''Advanced''' - Nielsen Simplified API integrated into a custom video player.
* '''Advanced''' - Nielsen Simplified API integrated into a custom video player.
** [https://engineeringportal.nielsen.com/docs/Special:Downloads Swift 4.0 Sample]
** [https://engineeringportal.nielsen.com/docs/Special:Downloads Swift 5.0 Sample]
** [https://engineeringportal.nielsen.com/docs/Special:Downloads Objective-C Sample]
** [https://engineeringportal.nielsen.com/docs/Special:Downloads Objective-C Sample]
** [https://engineeringportal.nielsen.com/docs/Special:Downloads Java/Android Studio Sample]
** [https://engineeringportal.nielsen.com/docs/Special:Downloads Java/Android Studio Sample]

Revision as of 17:06, 23 June 2020

Engineering Portal / Digital / DCR & DTVR / DCR 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. It supports a variety of Nielsen Measurement Products like Digital in TV Ratings, Digital Content Ratings (DCR & DTVR), and Digital Ad Ratings (DAR). Nielsen SDKs are also equipped to measure static content and can track key life cycle events of an application like:

  • Application launch events and how long app was running

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

This guide covers implementation steps for iOS using Xcode utilizing the Standard Nielsen SDK for DCR.

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.

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.

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.

Sample SDK Initialization Code

Swift 4.0 Example:

NielsenInit.swift

import Foundation
import NielsenAppApi

class NielsenInit : NSObject {
    class func createNielsenApi(delegate: NielsenAppApiDelegate) -> NielsenAppApi?{
        
        let appInformation:[String: String] = [
            "appid": "PDA7D5EE6-B1B8-4123-9277-2A788XXXXXXX",
            "nol_devDebug": "DEBUG"
        ]       
        return NielsenAppApi(appInfo:appInformation, delegate:delegate)
    }
}

Sample code using AVPlayer

ViewController.swift

class ViewController: UIViewController, NielsenAppApiDelegate, AVPlayerViewControllerDelegate  {

// your code//    

  override func viewDidLoad() {
        super.viewDidLoad()

        //Getting the instance of NielsenApi
        self.nielsenApi = NielsenInit.createNielsenApi(delegate: self)

            }
  }

Objective C =

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 "NielsenInit.h"
#import <NielsenAppApi/NielsenEventTracker.h>

@implementation NielsenInit

+ (NielsenAppApi *)createNielsenAppApiWithDelegate:(id<NielsenAppApiDelegate>)delegate
{    
    //Initialising the NielsenEventTracker class by passing app information which returns the instance of NielsenEventTracker.
    
    NSDictionary *appInformation = @{ @"appid": @"PDA7D5EE6-B1B8-4123-9277-2A788XXXXXXX",
                            @"nol_devDebug": @"DEBUG" };
    
    return [[NielsenAppApi alloc] initWithAppInfo:appInformation delegate:delegate];
}

@end


The following would be the NielsenInit.h file:

#import <Foundation/Foundation.h>

@class NielsenAppApi;
@protocol NielsenAppApiDelegate;

@interface NielsenInit : NSObject

+ (NielsenAppApi *)createNielsenAppApiWithDelegate:(id<NielsenAppApiDelegate>)delegate;

@end

Sample Code:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        
    //Getting the instance of Nielsen SDK
    nielsenApi = [NielsenInit createNielsenAppApiWithDelegate:nil];

}}


APP SDK Error & Event Codes

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

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.

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

Swift

let contentMetadata = [
    "type": "content",
    "assetid": "C77664",
    "title": "Program S2, E3",
    "isfullepisode": "Yes",
    "program": "Program Name",
    "length": "3600",
    "airdate": "20200321 10:05:00",
    "adloadtype": "2",
    "segB": "CustomSegmentValueB", //optional
    "segC": "CustomSegmentValueC", //optional
    "crossId1": "Standard Episode ID", //optional
    "crossId2": "Content Originator" //optional
];

Objective C

 
NSDictionary * contentMetadata = @ {
    @ "type": @ "content",
    @ "assetid": @ "C77664",
    @ "title": @ "S2,E3",
    @ "isfullepisode": @ "y",  
    @ "program": @ "Program Name",
    @ "length": @ "3600",
    @ "airdate": @ "20200321 10:05:00",
    @ "adloadtype": @ "2",
    @ "segB": @ "CustomSegmentValueB", //optional
    @ "segC": @ "CustomSegmentValueC", //optional
    @ "crossId1": @ "Standard Episode ID", //optional
    @ "crossId2": @ "Content Originator" //optional
}


Content Metadata

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

Keys Description Values Required Provider
type Type of asset For Video use: content
For Static or text static
Yes Nielsen
assetid Unique ID assigned to asset
Note: Refrain from using the following special characters (Special Characters).
Examples:
BBT345a234
CBSs5e234F2021
Yes Client
program Complete program or movie title
(no abbreviations or shorthand)
Note: there is a 25 character limit.
The Big Bang Theory
TheBigBangTheory
The Dark Knight
TheDarkKnight
Yes Client
title Episode title with season and episode number (40 character limit)
(Formats accepted: S01E03, S1E3, S1 E3).
Examples:
The Pants Alternative S03E18
The Pants Alternative S3E18
The Pants Alternative S3 E18
Can also accept: S3E18
Not Valid: 318 or 0318
Yes Client
crossId1 Gracenote TMS ID (If available) should be passed for all telecasted content for clients using the Gracenote solution for proper matching purposes.
Note: The TMS ID will be a 14 character string. Normally leading with 2 alpha characters ('EP', 'MV', 'SH' or 'SP'), followed by 12 numbers.
The TMS ID will be a 14 character string.
Normally being with 'EV,' 'EP', 'SH', 'SP', or 'MV'
Followed by 12 numbers after the initial two letter prefix.

The Giant Morning Show: SH009311820022
The Pants Alternative Episode : EP009311820061
Optional Nielsen
crossId2 Populated by content distributor to contribute viewing from that distributor to the given content originator. Custom
For a full list of acceptable values, please contact your Nielsen reprentative.
Yes, for distributors Nielsen
length Length of content in seconds
Note: Integers and decimal values are acceptable for the length parameter.
Examples:

For standard VOD content - 300 to represent 5 minutes, 1320 to represent 22 minutes, etc.
If DAI live stream of a discrete program (Live Event/Sporting Event), pass length of content. See example for standard VOD content above.
If unknown DAI live steam, pass a value of 0.

Yes Client
airdate Original broadcast or release date for the program
For USA, date should be EST
Outside USA, date should be local time.
If not applicable or available, original broadcast or release date for the Program.
Acceptable Formats:
YYYY-MM-DDTHH:MI:SS
YYYY-MM-DDHH:MI:SS
YYYY-MM-DDTHH:MI:SS+xx:xx
YYYY-MM-DDTHH:MI:SS-xx:xx
YYYYMMDDHH:MI:SS
YYYYMMDD HH:MI:SS
MM-DD-YYYY
MM/DD/YYYY
YYYYMMDD
Yes Client
isfullepisode Full episode flag to identify differences between long form content. y- full episode, n- non full episode(clip,teaser,promo,etc.)

Also accept:
lf or yes- longform
sf or no- shortform

Yes Nielsen
adloadtype Type of ad load:

1 Linear – matches TV ad load
2 Dynamic – Dynamic Ad Insertion (DAI)

2 - DCR measures content with dynamic ads Yes Nielsen
segB One of two custom segment for the clients granular reporting within a brand. Examples:
Genre - horror, comedy, etc.
Timeslot - primetime, daytime, etc.
News type - breakingnews, weather, etc.
Optional Client
segC One of two custom segment for the clients granular reporting within a brand. Examples:
Genre - horror, comedy, etc.
Timeslot - primetime, daytime, etc.
News type - breakingnews, weather, etc.
Optional Client

Custom segments (segB and segC) can be used to aggregate video and/or static content within a single Brand to receive more granular reports within a brand.

Examples regarding usage of segments within SDK:

  • All comedy clips and stories for a Brand rolled into a "Comedy" segment
  • genre grouping content by Comedy vs. Drama
  • group related Text + Video content - i.e. for a show that has a lot of - static pages associated with it
  • packaging based on how clients sell inventory
  • grouping related types of content either by genre, category or platform.


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

Example Ad Object

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

Configure Static Metadata if Applicable

The below is to measure Static Content.

The Nielsen reserved keys are:

Key Description Data Type Value Required?
type asset type fixed 'static' Yes
section section of each site (e.g. section value should be first level in page URL: website.com/section). Limit to 25 unique values dynamic custom Yes
segA custom segment for reporting: Limit to 25 unique values across custom segments (segA + segB + segC) dynamic custom No
segB custom segment for reporting: Limit to 25 unique values across custom segments (segA + segB + segC) dynamic custom No
segC custom segment for reporting: Limit to 25 unique values across custom segments (segA + segB + segC) dynamic custom No

The values passed through the Nielsen keys will determine the breakouts that are seen in reporting. The custom segments (A, B & C) will roll into the sub-brand. To not use custom segments A, B and C, do not pass any value in these keys.

Aggregation Limits There are limits on the number of unique values that can be aggregated on in reporting. The specific limitations by key are:

Key Aggregation Limit
section maximum of 25 unique values (section <= 25)
segA Maximum number of unique values allowed across segA, segB, and segC is 25 (segA + segB + segC<= 25)
segB Maximum number of unique values allowed across segA, segB, and segC is 25 (segA + segB + segC<= 25)
segC Maximum number of unique values allowed across segA, segB, and segC is 25 (segA + segB + segC<= 25)

Example Static Object

        let staticData =
            [
                "type": "static",
                "section": "Section Name",
                "segA": "segmentA",
                "segB": "segmentB",
                "segC": "en-us"
        ]

Configure API Calls

Sample API Sequence

A Sample API sequence could follow this flow:

Type Sample code Description
On App Start
NielsenInit.createMainBrandApi(delegate: self)
self.data = loadStaticMetadata()
self.nielsenMeter .loadMetadata(self.data)
// Pass Static Metadata here if applicable
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.

Swift

nielsenAppApi?.play();

Objective C

   [nielsenAppApi play:()];


loadMetadata

Swift

self.nielsenAppApi?.loadMetadata(contentMetadata)

Objective C

[nielsenApi loadMetadata:(contentMetadata)];


playheadPosition

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);
            }
        }
    }

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)];
    }];
}


stop

Swift

nielsenApi.stop()

Objective C

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

Swift

nielsenApi.end()

Objective C

[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. Please check the "Implementation" section for a comparison of the three flavors. Implementing opt-out for the three flavors are different:

  1. Global iOS SDK Opt-out - managed by AppTracking or Limit Ad Tracking setting on device.
  2. Global iOS SDK No Ad Framework Opt-out - Direct call to SDK. Can be used without the Ad Framework.
  3. Global iOS SDK No ID Opt-out - 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”.


If you are implementing on AppleTV here are your Opt Out verbiage options : https://engineeringportal.nielsen.com/docs/DCR_Video_%26_Static_CTV_Device_SDK_Privacy

Sample Code for Global Build

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)
        }}
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]]];
}}

Global iOS SDK No Ad Framework Opt-out

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 user and 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. The steps are 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
      

Sample code for No Ad Framework Build

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

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


Global iOS SDK No ID Opt-out

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

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: