DTVR iOS SDK: Difference between revisions

From Engineering Client Portal

(fixed mention of playhead position for DTVR)
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]]
== 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]]), [[Digital Ad Ratings]] (DAR), and [[Digital Audio]]. 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.
If the content being played contains ID3 tags, when played on a mobile device or within a browser, these tags can be sent to Nielsen for collection/processing via the Nielsen SDK. 
<blockquote>
VOD in TV Ratings (formally knows as Recently Telecast VOD) support is now available; however, you must notify your Nielsen Technical Account Manager to ensure accurate reporting.
</blockquote>


== Prerequisites ==
== Prerequisites ==
To start using the App SDK, the following items are required:
To start using the App SDK, the following details are required:
* '''App ID (appid):''' Unique ID assigned to the player/site and configured by product.
* '''sfcode:''' Unique identifier for the environment that the SDK should point to.
* '''Nielsen SDK:''' The Nielsen SDK package contains a variety of sample players for your reference.
If you do not have any of these prerequisites or if you have any questions, please contact our SDK sales support team.
Refer to [[Digital Measurement Onboarding]] guide for information on how to get a Nielsen App SDK and appid.
 
==  Implementation ==
This guide covers implementation steps for iOS using Xcode utilizing the Standard Nielsen SDK for DTVR.
 
== Setting up your  Development Environment  ==
=== 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, the SDK uses the WKWebView class instead of the deprecated UIWebView as per Apple guidelines.
 
<blockquote>'''Note''': All communications between the SDK and the Census (Collection Facility) use HTTPS.</blockquote>
 
=== Importing Frameworks ===
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.
* UIKit.framework
* Foundation.framework
* AdSupport.framework
* JavascriptCore.framework
* WebKit.framework
* SystemConfiguration.framework
* Security.framework
** Nielsen Analytics framework makes use of a number of functions in this library.
* AVFoundation.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'''
* 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
*Xcode will prompt you to create a bridging header.
[[File:bridgingheader 2x.png|600px|center|link=]]
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.
 
== 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. (Version 4.0 for Android)
 
* A maximum of four SDK instances per appid are supported.
* When four SDK instances exist, you must destroy an old instance before creating a new one.
 
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"
|-
|-
! style="width: 30px;" |
! Parameter / Argument !! Description !! Source !! Required? !! Example
! style="width: 15%;" | Item
! Description
! Source
|-
|-
|| ☑ || '''App ID (appid)''' || Unique ID assigned to the player/site and configured by product. || Contact Nielsen
| appid || Unique id for the application assigned by Nielsen. It is GUID data type.|| Nielsen-specified || Yes || PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
|-
|-
|| || '''sfcode''' || Environment that the SDK must point to || Contact Nielsen
| appname || Name of the application || Client-defined || Optional; automatically detected in SDK 6.0.0.4 and above || Nielsen Sample App
|-
|-
|| || '''Nielsen SDK''' || Includes SDK libraries and '''sample implementation'''; ''See [[iOS SDK Release Notes]]'' || [[Special:Downloads|Download]]
| sfcode || Nielsen collection facility to which the SDK should connect.
|| Nielsen-specified || Yes || us
|-
|containerID || View ID of the UI element used as player view in application for Viewability ||Client-defined||Optional||"1234567"
|-
| nol_devDebug || Enables Nielsen console logging. Only required for testing
|| Nielsen-specified || Optional || "DEBUG"
|}
|}
If you do not have any of these pre-requisites or if you have any questions, please contact our SDK sales support team.
Refer to [[Digital Measurement Onboarding]] for more information on how to get a Nielsen App SDK and appid.


== Import Library ==
==== Debug flag for development environment ====
Refer to [[iOS SDK API Reference#Importing Frameworks|Importing Frameworks]] for information on importing libraries.
Player application developers / integrators can use Debug flag to check whether an App SDK API call made is successful. To activate the Debug flag,
* The latest version of App SDK allows instantiating multiple instances of App SDK object and can be used simultaneously without any issues.
Pass the argument <code>@"nol_devDebug":@"INFO"</code>, 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.
<blockquote>'''Note''': DO NOT activate the Debug flag in a production environment.</blockquote>
 
=== Sample SDK Initialization Code ===
{{ExampleCode|
|Swift  =
Swift 4.0 Example:
<code>NielsenInit.swift</code>
<syntaxhighlight lang="swift">
import Foundation
import NielsenAppApi


== Initialize SDK ==
class NielsenInit : NSObject {
Initialize App SDK as soon as the application is launched. Refer to [[iOS SDK API Reference#Initialization|Initialization]] for details on initializing an AppSDK object and the parameters required.
    class func createNielsenApi(delegate: NielsenAppApiDelegate) -> NielsenAppApi?{
       
        let appInformation:[String: String] = [
           
            "appid": "PDA7D5EE6-B1B8-4123-9277-2A788XXXXXXX",
            "sfcode": "us",
            "nol_devDebug": "DEBUG"
            "containerId": String(containerId)  //Keep container id unique constant, you can use tag property of player.
        ]
       
        return NielsenAppApi(appInfo:appInformation, delegate:delegate)
    }
}
</syntaxhighlight>
 
 
Sample code using AVPlayer.
<code>ViewController.swift</code>
 
<syntaxhighlight lang="swift">
class ViewController: UIViewController, NielsenAppApiDelegate, AVPlayerViewControllerDelegate  {
 
// your code//   
 
  override func viewDidLoad() {
        super.viewDidLoad()
 
        //Getting the instance of NielsenApi
        self.nielsenApi = NielsenInit.createNielsenApi(delegate: self)
 
            }
  }
</syntaxhighlight>
|Objective C =  
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>
<syntaxhighlight lang="objective-c">   
#import "NielsenInit.h"
#import <NielsenAppApi/NielsenEventTracker.h>
 
@implementation NielsenInit
 
+ (NielsenEventTracker *)createNielsenEventTrackerWithDelegate:(id<NielsenEventTrackerDelegate>)delegate
{
    //Initialising the NielsenEventTracker class by passing app information which returns the instance of NielsenEventTracker.
   
    NSDictionary *appInformation = @{ @"appid": @"PDA7D5EE6-B1B8-4123-9277-2A788XXXXXXX",
                            @"appversion": @"1.0",
                            @"sfcode": @"us",
                            @"nol_devDebug": @"DEBUG",
                            @"containerId": @"1" };
   
    return [[NielsenEventTracker alloc] initWithAppInfo:appInformation delegate:delegate];
}
 
@end
</syntaxhighlight>
 
 
The following would be the <code>NielsenInit.h</code> file:
<syntaxhighlight lang="objective-c">
 
#import <Foundation/Foundation.h>
 
@class NielsenEventTracker;
@protocol NielsenEventTrackerDelegate;
 
@interface NielsenInit : NSObject
 
+ (NielsenEventTracker *)createNielsenEventTrackerWithDelegate:(id<NielsenEventTrackerDelegate>)delegate;
 
@end
</syntaxhighlight>
 
}}
 
== Initializing the Nielsen AppSDK to measure the Viewability ==
The integrator to support the viewability metrics in the application has to provide a tag value of the player view to let Nielsen AppSDK know that there is a player that needs to be tracked. It’s called the ‘containerId’ and it should be passed in application info dictionary as string while initializing the Nielsen AppSDK.
 
==== Android ====
{| class="wikitable"
|-
! # !! Parameter Name !! Description !! Supported Values !! Example
|-
| 1 || containerId ||View ID of the UI element used as player view in application. getId() method of View class can be used to get this value. ||A positive integer used to identify the view. || 2131558561
|}
 
==== iOS ====
{| class="wikitable"
|-
! # !! Parameter Name !! Description !! Supported Values !! Example
|-
| 1 || containerId ||The tag of the UIView that represents the Player View ||The string value representing the NSInteger value with maximum value of NSIntegerMax that is related on 32- or 64-bit applications. || "100" <br> "2131558561"
|}
 
For iOS it is required to link additional frameworks that are needed for viewability engine:<br>
<code>JavaScriptCore.framework</code> <br>
<code>WebKit.framework</code>
 
The Nielsen AppSDK uses a tracking WebView (TWV) approach. For more information on Viewability, please refer to [https://engineeringportal.nielsen.com/docs/Implementing_Viewability_with_AppSDK Implementing Viewability with AppSDK.]
 
== APP SDK Error & Event Codes ==
To view the Error and Event codes for iOS and Android, please review the [[APP SDK Event Codes|App SDK Event Code]] Reference page.
 
== Content Metadata and SDK Events ==
=== Content Metadata ===
Content metadata should remain constant throughout the completion of an episode or live stream.
{| class="wikitable"
|-
! Key !! Description !! Values !! Required
|-
| channelName || Any string representing the channel/stream || 32-character free-form text ||
|-
| type || type of asset || "content" || ✓
|-
| adModel || linear vs dynamic ad model || 1 = Linear  matches TV ad load      || ✓
|-
|}
<syntaxhighlight lang="objectivec">   
- (NSDictionary *)loadChannelInfo
{
    //Loading Channel Info.   
    NSString *strUrl = self.url.absoluteString; 
    NSDictionary *channel = @{  @"channelName" : @"TheGreatBigMovie": strUrl }; 
    return channel;
}
- (NSDictionary *)loadDtvr{
   
    //Loading DTVR data 
    NSDictionary *dtvr = @{ @"adModel":@"1" , 
                            @"type":@"content",}; 
    return dtvr;
}
    </syntaxhighlight>
 
=== SDK Events ===
[[File:appsdkTimeline-DTVR-V2.png|icon]]
{| class="wikitable"
|-
! Event !! Parameter !! Description
|-
| 'loadMetadata' || content/ad metadata object || Needs to be called at the beginning of each asset to pass type, channelName, and adModel.
|-
|'play'||program or feed name||Call when starting or resuming a streaming session.
|-
| 'stop' || playhead position || Call when content or ads complete playing and pass playhead position
|-
| 'sendID3' || Used to send the ID3 tag payload retrieved from the stream || Needs to be called at the beginning of playback
||
|-
| 'end' || Content end || Call when the current video asset completes playback or when a stream is interrupted. <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.
|}


== Configure and fire API calls ==
=== Configure API calls - play ===
=== Configure API calls - play ===
Use [[play]] to pass the channel descriptor information through channelName parameter when the user taps the '''Play''' button on the player.
{{ExampleCode|
* <code>channelName</code> is a 32-character free-form text field containing the name of the program or feed being sent (such as ESPN2, Food Network, etc.)
|Objective C = <syntaxhighlight lang="objective-c">   [nielsenAppApi play:(loadChannelInfo)];</syntaxhighlight>
Call [[play]] with <code>channelName</code> JSON as below.
|Swift = <syntaxhighlight lang="swift">nielsenAppApi?.play(loadChannelInfo);</syntaxhighlight>
<syntaxhighlight lang="json">   {
}}
      "channelName": "TheMovieTitle"
    }</syntaxhighlight>


=== Configure API calls - loadMetadata ===
=== Configure API calls - loadMetadata ===
Use [[loadMetadata]] to pass ‘content’ and ‘ad’ [[Digital Measurement Metadata]]. The CMS data must be passed as a JSON object.
Use <code>loadMetadata</code> to pass ‘content’ and ‘ad’ <code>Digital Measurement Metadata</code>. The CMS data must be passed as a JSON object.
<syntaxhighlight lang="swift">   – (void) loadMetadata :(id)metadata;</syntaxhighlight>
{{ExampleCode|
Refer to [[loadMetadata]] for the list of parameters to be passed in the JSON object.
|Objective C = <syntaxhighlight lang="objective-c">[nielsenApi loadMetadata:(loadDtvr)];</syntaxhighlight>
Call [[loadMetadata]] after the first play call. Call [[loadMetadata]] with JSON metadata for the active content as below.
|Swift = <syntaxhighlight lang="swift">self.nielsenAppApi?.loadMetadata(loadDtvr)</syntaxhighlight>
<syntaxhighlight lang="json">   {
}}
      "type": "content",
      "adModel": "1"
    }</syntaxhighlight>


=== Configure API calls - sendID3 ===
=== Configure API calls - sendID3 ===
[[sendID3]] API is a receiver for timed metadata events (ID3 tags) provided through iOS’s NSNotificationCenter notification system. This API filters out Nielsen-specific ID3 tags from the system and buffers the data for transfer to Nielsen’s collection facility.
[[sendID3]] API is a receiver for timed metadata events (ID3 tags) provided through iOS’s NSNotificationCenter notification system. This API filters out Nielsen-specific ID3 tags from the system and buffers the data for transfer to Nielsen’s collection facility.
==== Sample ID3 tags ====
{{ExampleCode|
|Objective C = <syntaxhighlight lang="objective-c">[nielsenApi sendID3:extraString];</syntaxhighlight>
|Swift = <syntaxhighlight lang="swift"> [nielsenApi sendID3:extraString];</syntaxhighlight>}}
'''Sample ID3 tags'''
* <code>www.nielsen.com/X100zdCIGeIlgZnkYj6UvQ==/X100zdCIGeIlgZnkYj6UvQ==/AAAB2Jz2_k74GXSzx4npHuI_<wbr />JwJd3QSUpW30rDkGTcbHEzIMWleCzM-uvNOP9fzJcQMWQLJqzXMCAxParOb5sGijSV9dNM3QiBniJYGZ5GI-lL1fXTTN0IgZ4iWBmeRiPpS9AAAAAAAAAAAAAAAAAAAAAFJWFM5SVhTONNU=/00000/00000/00</code>
* <code>www.nielsen.com/X100zdCIGeIlgZnkYj6UvQ==/X100zdCIGeIlgZnkYj6UvQ==/AAAB2Jz2_k74GXSzx4npHuI_<wbr />JwJd3QSUpW30rDkGTcbHEzIMWleCzM-uvNOP9fzJcQMWQLJqzXMCAxParOb5sGijSV9dNM3QiBniJYGZ5GI-lL1fXTTN0IgZ4iWBmeRiPpS9AAAAAAAAAAAAAAAAAAAAAFJWFM5SVhTONNU=/00000/00000/00</code>
* <code>www.nielsen.com/X100zdCIGeIlgZnkYj6UvQ==/R8WHe7pEBeqBhu8jTeXydg==/AAICoyitYqlxT7n6aZ0oMCGhe<wbr />Fi4CXFp46AMUPZz1lMr_M9tr3_cjee1SHqxrOiVerMDLeyn9xzocZSKwi746Re8vNOtpNCAZjYABs_J0R25IHpvOc1HS8<wbr />QHGgD5TgOJeS6gX100zdCIGeIlgZnkYj6UvVJWFNhSVhTiPE0=/00000/46016/00</code>
* <code>www.nielsen.com/X100zdCIGeIlgZnkYj6UvQ==/R8WHe7pEBeqBhu8jTeXydg==/AAICoyitYqlxT7n6aZ0oMCGhe<wbr />Fi4CXFp46AMUPZz1lMr_M9tr3_cjee1SHqxrOiVerMDLeyn9xzocZSKwi746Re8vNOtpNCAZjYABs_J0R25IHpvOc1HS8<wbr />QHGgD5TgOJeS6gX100zdCIGeIlgZnkYj6UvVJWFNhSVhTiPE0=/00000/46016/00</code>
Refer to [[iOS SDK API Reference#Retrieving ID3 Tags|Retrieving ID3 Tags]] section to know more details.
Refer to [[iOS SDK API Reference#Retrieving ID3 Tags|Retrieving ID3 Tags]] section to know more details.


===Configure API calls - stop ===
=== Configure API calls - stop ===
Call [[stop]] in case of interruptions during playback like flight mode, Wi-Fi toggle, etc. Call [[play]] when resuming the stream / starting the new stream.
Call <code>stop</code> in case of interruptions during playback like flight mode, Wi-Fi toggle, etc. Call <code>play</code> when resuming the stream / starting the new stream.
{{ExampleCode|
|Objective C = <syntaxhighlight lang="objective-c">[nielsenApi stop];</syntaxhighlight>
|Swift = <syntaxhighlight lang="swift">nielsenApi.stop()</syntaxhighlight>
}}


===Configure API calls - end ===
=== Configure API calls - end ===
Call [[end]] only at the end of playback.
Call [[end]] only at the end of playback.
{{ExampleCode|
|Objective C = <syntaxhighlight lang="objective-c">[nielsenApi end];</syntaxhighlight>
|Swift = <syntaxhighlight lang="swift">nielsenApi.end()</syntaxhighlight>
}}
== Retrieving ID3 Tags ==
ID3 tags have a payload of about 249 characters and start with "www.nielsen.com".
ID3 tags are extracted by observing a property called timedMetadata on the iOS player item. Now this is done via a concept called KVO (Key Value Observing), where you register interest in a property, and the runtime will let you know when it has changed.
Both the iOS native players have the ability to extract ID3 tags, If any other player apart from iOS native players (AVPlayer, MPMoviePlayer) is used, check and ensure that the player has the capability to extract ID3 tags.
=== Examples of extracting ID3 tags from the iOS Native Player ===
{{ExampleCode|
|Objective C = <syntaxhighlight lang="objective-c">
    //Adding observer to player to track play,pause and reverse
    [player addObserver:self
            forKeyPath:@"rate"
                options:(NSKeyValueObservingOptionNew)
                context:nil];
  </syntaxhighlight>
------------------------------
  <syntaxhighlight lang="objective-c">     
        //Setting observer to track timedMetadata
        [player addObserver:self
                forKeyPath: timedMetadataKey
                    options: (NSKeyValueObservingOptionNew)
                    context: &TimedMetadataObserverContext];
  </syntaxhighlight>
------------------------------
  <syntaxhighlight lang="objective-c">   
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                      context:(void *)context
{
    if(keyPath == timedMetadataKey){
        if(context == &TimedMetadataObserverContext){
           
            id newMetadataArray = [change objectForKey:NSKeyValueChangeNewKey];
            if (newMetadataArray != [NSNull null])
            {
                array = newMetadataArray;
                for (AVMetadataItem *metadataItem in array)
                {
                    //Handling TimedMetadata
                    [self handleTimedMetadata: metadataItem];
                }
            }
           
        }
    }
</syntaxhighlight>
------------------------------
  <syntaxhighlight lang="objective-c">   
- (void)handleTimedMetadata:(AVMetadataItem *)timedMetadata
{
    // We expect the content to contain plists encoded as timed metadata
    // AVPlayer turns these into NSDictionaries
   
    id extraAttributeType = [timedMetadata extraAttributes];
    NSString *extraString = nil;
    if ([extraAttributeType isKindOfClass:[NSDictionary class]])
    {
        extraString = [extraAttributeType valueForKey:@"info"];
    }
    else if ([extraAttributeType isKindOfClass:[NSString class]])
    {
        extraString = extraAttributeType;
    }
   
    NSString *key = [NSString stringWithFormat:@"%@", [timedMetadata key]];
   
    //If tag starts with "www.nielsen.com", then only sending to SDK
    if ([key isEqualToString:@"PRIV"] && [extraString rangeOfString:@"www.nielsen.com"].length > 0)
    {
       
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [nielsenApi sendID3:extraString];
        });
    }
}
</syntaxhighlight>
|Swift = <syntaxhighlight lang="swift">
      //Setting observer to track timedMetadata
            player.addObserver(self, forKeyPath: timedMetadataKey, options: NSKeyValueObservingOptions.new, context: &TimedMetadataObserverContext)</syntaxhighlight>
------------------------------------------------------
<syntaxhighlight lang="swift">
  override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
       
        if keyPath == timedMetadataKey {
            if(context == &TimedMetadataObserverContext){
                if change != nil {
                    let timedMetadataArray = change![.newKey]
                    if timedMetadataArray != nil && (timedMetadataArray! as AnyObject) is Array<Any> {
                        for item in timedMetadataArray as! [AVMetadataItem]  {
                            //Handling TimedMetadata
                            self.handleTimedMetadata(metadataItem: item)
                        }
                    }
                }
            }
        }
</syntaxhighlight>
------------------------------------------------------
<syntaxhighlight lang="swift">
func handleTimedMetadata(metadataItem: AVMetadataItem) {
        guard let extraAttributeType = metadataItem.extraAttributes else {
            return
        }
        let info : AVMetadataExtraAttributeKey = AVMetadataExtraAttributeKey(rawValue: "info")
        let extraString = extraAttributeType[info] as AnyObject
        let key = metadataItem.key as! String
       
        //If tag starts with "www.nielsen.com", then only sending to SDK
        if key == "PRIV" && extraString.range(of: "www.nielsen.com").length > 0 {
           
            DispatchQueue.global(qos: .default).async { () -> Void in
                self.nielsenApi?.sendID3(extraString as! String)
            }
        }
    }
   
</syntaxhighlight>
}}
== Life cycle of SDK instance ==
Life cycle of SDK instance includes four general states:
# '''Initial state''' – The SDK is not initialized and hence, not ready to process playing information. Once the SDK is moved out of this state, it needs instantiation of the new SDK instance in order to get the instance in the '''Initial state'''.
# '''Idle state''' – The SDK is initialized and is ready to process playing information. Once Initialized, the SDK instance is not processing any data, but is listening for the play event to occur.
# '''Processing state''' – The SDK instance is processing playing information. 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>'''stop'''</code> – Call this API when the playback is paused, switches between content and ad (within the same content playback) or encounters interruptions.
## <code>'''end'''</code> – SDK instance exits from Processing state when this API is called.
# '''Disabled state''' – The SDK instance is disabled and is not processing playing information. SDK instance moves into this state in one of the following scenarios.
## Initialization fails
## <code>'''appDisableApi'''</code> is set to <code>true</code>  ''(This is testing purposes only.  Not for User Opt-Out.)''
<blockquote>'''Note:''' For API Version 5.1 and above, App SDK will fire data pings and continue measurement even after the user has opted out from Nielsen measurement on a device. The data ping will be marked as opted-out ping.</blockquote>
'''Note''': In case of any interruptions during playback due to alarm, calendar, call, flight mode, Wi-Fi toggle, channel change, etc., call <code>stop</code> to stop the measurement.
== Handling Foreground and Background states ==
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:]
Foreground/Background state measurement is a requirement of Nielsen AppSDK implementation which is especially crucial for static measurement.


== Interruptions during playback ==
== Interruptions during playback ==
Line 71: Line 462:
* Unplugging of headphone
* Unplugging of headphone
In case of encountering one of the above interruptions, the player application needs to
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 ID3 events.
* Call <code>stop</code> immediately (except when content is buffering) and withhold sending playhead position.
* Start sending pings – [[loadMetadata]] and [[sendID3]] for the new viewing session, once the playback resumes.
* Call <code>play</code> once the playback resumes.
Please see the [[Digital Measurement FAQ]] for more details
 
== 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.
 
{{Template:iOS_Privacy_and_Opt-Out}}
 
== Going Live ==
Following Nielsen testing, users need to make one update to the initialization call to ensure that the site is being measured properly.
 
# '''Debug Logging''': Disable logging by deleting <code>{nol_sdkDebug: 'DEBUG'}</code> from initialization call.
 
'''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.
 
== Sample Applications ==
The below sample applications have been designed to show the Simplified API's functionality and are broken into two distinct categories:
* '''Basic''' - To show the functionality of the Nielsen Simplified API using a standard no-frills player.
** [[Swift Basic Sample|Swift 4.0 Sample]]
** [[Objective-c Basic example|Objective-C Sample]]
** [[Android Basic example|Android Studio Example]]


== Nielsen Measurement Opt-Out Implementation ==
* '''Advanced''' - Nielsen Simplified API integrated into a custom video player is contained in the ZIP package.
As a global information and measurement leader, we are committed to protecting the privacy and security of the data we collect, process and use. Our digital measurement products are not used to identify the consumer in any way, but they help us and our clients measure and analyze how consumers engage with media across online, mobile and emerging technologies, and offer insights into consumer behavior.
* When the app user wants to opt in or opt out of Nielsen measurement, a new dynamic page (with content string obtained from [[optOutURL]]) should be displayed.
* Use [[optOutStatus]] to retrieve the device’s Opt-Out status.
* This Opt-out page should be displayed in a webview (within the app) and not in any external browser.
* Capture the user’s selection in this page and pass it to the SDK through [[userOptOut]] for Nielsen to save the user’s preference.
<!-- * For more details, refer to [[iOS SDK API Reference#iOS Opt-Out Implementation|iOS SDK API Reference - iOS Opt-Out Implementation]] and Nielsen Digital Privacy. -->


== Testing an Implementation - App ==
== Testing an Implementation - App ==
See [[Digital Measurement Testing]].
See [[Digital Measurement Testing]].

Revision as of 21:06, 2 October 2018

Engineering Portal / Digital / DCR & DTVR / DTVR 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), Digital Ad Ratings (DAR), and Digital Audio. 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.

If the content being played contains ID3 tags, when played on a mobile device or within a browser, these tags can be sent to Nielsen for collection/processing via the Nielsen SDK.

VOD in TV Ratings (formally knows as Recently Telecast VOD) support is now available; however, you must notify your Nielsen Technical Account Manager to ensure accurate reporting.

Prerequisites

To start using the App SDK, the following details are required:

  • App ID (appid): Unique ID assigned to the player/site and configured by product.
  • sfcode: Unique identifier for the environment that the SDK should point to.
  • Nielsen SDK: The Nielsen SDK package contains a variety of sample players for your reference.

If you do not have any of these prerequisites or if you have any questions, please contact our SDK sales support team. Refer to Digital Measurement Onboarding guide for information on how to get a Nielsen App SDK and appid.

Implementation

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

Setting up your Development Environment

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, the SDK uses the WKWebView class instead of the deprecated UIWebView as per Apple guidelines.

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

Importing Frameworks

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.

  • UIKit.framework
  • Foundation.framework
  • AdSupport.framework
  • JavascriptCore.framework
  • WebKit.framework
  • SystemConfiguration.framework
  • Security.framework
    • Nielsen Analytics framework makes use of a number of functions in this library.
  • AVFoundation.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

Example

  • Extract “NielsenAppApi.Framework” from the Nielsen App SDK sample app and copy it to Frameworks folder of the Xcode project.
  • Add the code -#import NielsenAppApi/NielsenAppApi.h to the View Controller’s header file.

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


Using Swift 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
  • Xcode will prompt you to create a bridging header.
bridgingheader 2x.png

Once this file has been created, you need to add the following:

#import <NielsenAppApi/NielsenAppApi.h>

Using Objective-C Add the code

#import <NielsenAppApi/NielsenAppApi.h>

to the View Controller’s header file.

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. (Version 4.0 for Android)

  • A maximum of four SDK instances per appid are supported.
  • When four SDK instances exist, you must destroy an old instance before creating a new one.

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

  • The appid is provided by the Nielsen Technical Account Manager (TAM). The appid is a GUID data type and is specific to the application.
Parameter / Argument Description Source Required? Example
appid Unique id for the application assigned by Nielsen. It is GUID data type. Nielsen-specified Yes PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
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. Nielsen-specified Yes us
containerID View ID of the UI element used as player view in application for Viewability Client-defined Optional "1234567"
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

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",
            "sfcode": "us",
            "nol_devDebug": "DEBUG"
            "containerId": String(containerId)   //Keep container id unique constant, you can use tag property of player.
        ]
        
        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

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

@end


The following would be the NielsenInit.h file:

#import <Foundation/Foundation.h>

@class NielsenEventTracker;
@protocol NielsenEventTrackerDelegate;

@interface NielsenInit : NSObject

+ (NielsenEventTracker *)createNielsenEventTrackerWithDelegate:(id<NielsenEventTrackerDelegate>)delegate;

@end


Initializing the Nielsen AppSDK to measure the Viewability

The integrator to support the viewability metrics in the application has to provide a tag value of the player view to let Nielsen AppSDK know that there is a player that needs to be tracked. It’s called the ‘containerId’ and it should be passed in application info dictionary as string while initializing the Nielsen AppSDK.

Android

# Parameter Name Description Supported Values Example
1 containerId View ID of the UI element used as player view in application. getId() method of View class can be used to get this value. A positive integer used to identify the view. 2131558561

iOS

# Parameter Name Description Supported Values Example
1 containerId The tag of the UIView that represents the Player View The string value representing the NSInteger value with maximum value of NSIntegerMax that is related on 32- or 64-bit applications. "100"
"2131558561"

For iOS it is required to link additional frameworks that are needed for viewability engine:
JavaScriptCore.framework
WebKit.framework

The Nielsen AppSDK uses a tracking WebView (TWV) approach. For more information on Viewability, please refer to Implementing Viewability with AppSDK.

APP SDK Error & Event Codes

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

Content Metadata and SDK Events

Content Metadata

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

Key Description Values Required
channelName Any string representing the channel/stream 32-character free-form text
type type of asset "content"
adModel linear vs dynamic ad model 1 = Linear matches TV ad load
    
- (NSDictionary *)loadChannelInfo
{
    //Loading Channel Info.    
    NSString *strUrl = self.url.absoluteString;  
    NSDictionary *channel = @{  @"channelName" : @"TheGreatBigMovie": strUrl };   
    return channel;
}
- (NSDictionary *)loadDtvr{
    
    //Loading DTVR data  
    NSDictionary *dtvr = @{ @"adModel":@"1" ,  
                            @"type":@"content",};  
    return dtvr;
}

SDK Events

icon

Event Parameter Description
'loadMetadata' content/ad metadata object Needs to be called at the beginning of each asset to pass type, channelName, and adModel.
'play' program or feed name Call when starting or resuming a streaming session.
'stop' playhead position Call when content or ads complete playing and pass playhead position
'sendID3' Used to send the ID3 tag payload retrieved from the stream Needs to be called at the beginning of playback
'end' Content end Call when the current video asset completes playback or when a stream is interrupted.

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

Configure API calls - play

Swift

nielsenAppApi?.play(loadChannelInfo);

Objective C

   [nielsenAppApi play:(loadChannelInfo)];


Configure API calls - loadMetadata

Use loadMetadata to pass ‘content’ and ‘ad’ Digital Measurement Metadata. The CMS data must be passed as a JSON object.

Swift

self.nielsenAppApi?.loadMetadata(loadDtvr)

Objective C

[nielsenApi loadMetadata:(loadDtvr)];


Configure API calls - sendID3

sendID3 API is a receiver for timed metadata events (ID3 tags) provided through iOS’s NSNotificationCenter notification system. This API filters out Nielsen-specific ID3 tags from the system and buffers the data for transfer to Nielsen’s collection facility.

Swift

 [nielsenApi sendID3:extraString];

Objective C

[nielsenApi sendID3:extraString];


Sample ID3 tags

  • www.nielsen.com/X100zdCIGeIlgZnkYj6UvQ==/X100zdCIGeIlgZnkYj6UvQ==/AAAB2Jz2_k74GXSzx4npHuI_JwJd3QSUpW30rDkGTcbHEzIMWleCzM-uvNOP9fzJcQMWQLJqzXMCAxParOb5sGijSV9dNM3QiBniJYGZ5GI-lL1fXTTN0IgZ4iWBmeRiPpS9AAAAAAAAAAAAAAAAAAAAAFJWFM5SVhTONNU=/00000/00000/00
  • www.nielsen.com/X100zdCIGeIlgZnkYj6UvQ==/R8WHe7pEBeqBhu8jTeXydg==/AAICoyitYqlxT7n6aZ0oMCGheFi4CXFp46AMUPZz1lMr_M9tr3_cjee1SHqxrOiVerMDLeyn9xzocZSKwi746Re8vNOtpNCAZjYABs_J0R25IHpvOc1HS8QHGgD5TgOJeS6gX100zdCIGeIlgZnkYj6UvVJWFNhSVhTiPE0=/00000/46016/00

Refer to Retrieving ID3 Tags section to know more details.

Configure API calls - stop

Call stop in case of interruptions during playback like flight mode, Wi-Fi toggle, etc. Call play when resuming the stream / starting the new stream.

Swift

nielsenApi.stop()

Objective C

[nielsenApi stop];


Configure API calls - end

Call end only at the end of playback.

Swift

nielsenApi.end()

Objective C

[nielsenApi end];


Retrieving ID3 Tags

ID3 tags have a payload of about 249 characters and start with "www.nielsen.com".

ID3 tags are extracted by observing a property called timedMetadata on the iOS player item. Now this is done via a concept called KVO (Key Value Observing), where you register interest in a property, and the runtime will let you know when it has changed.

Both the iOS native players have the ability to extract ID3 tags, If any other player apart from iOS native players (AVPlayer, MPMoviePlayer) is used, check and ensure that the player has the capability to extract ID3 tags.

Examples of extracting ID3 tags from the iOS Native Player

Swift

 
      //Setting observer to track timedMetadata
            player.addObserver(self, forKeyPath: timedMetadataKey, options: NSKeyValueObservingOptions.new, context: &TimedMetadataObserverContext)

 
   override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if keyPath == timedMetadataKey {
            if(context == &TimedMetadataObserverContext){
                if change != nil {
                    let timedMetadataArray = change![.newKey]
                    if timedMetadataArray != nil && (timedMetadataArray! as AnyObject) is Array<Any> {
                        for item in timedMetadataArray as! [AVMetadataItem]  {
                            //Handling TimedMetadata
                            self.handleTimedMetadata(metadataItem: item)
                        }
                    }
                }
            }
        }

 
 func handleTimedMetadata(metadataItem: AVMetadataItem) {
        guard let extraAttributeType = metadataItem.extraAttributes else {
            return
        }
        let info : AVMetadataExtraAttributeKey = AVMetadataExtraAttributeKey(rawValue: "info")
        let extraString = extraAttributeType[info] as AnyObject
        let key = metadataItem.key as! String
        
        //If tag starts with "www.nielsen.com", then only sending to SDK
        if key == "PRIV" && extraString.range(of: "www.nielsen.com").length > 0 {
            
            DispatchQueue.global(qos: .default).async { () -> Void in
                self.nielsenApi?.sendID3(extraString as! String)
            }
        }
    }

Objective C

    //Adding observer to player to track play,pause and reverse
    [player addObserver:self
             forKeyPath:@"rate"
                options:(NSKeyValueObservingOptionNew)
                context:nil];

       
        //Setting observer to track timedMetadata
        [player addObserver:self
                 forKeyPath: timedMetadataKey
                    options: (NSKeyValueObservingOptionNew)
                    context: &TimedMetadataObserverContext];

     
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if(keyPath == timedMetadataKey){
        if(context == &TimedMetadataObserverContext){
            
            id newMetadataArray = [change objectForKey:NSKeyValueChangeNewKey];
            if (newMetadataArray != [NSNull null])
            {
                array = newMetadataArray;
                for (AVMetadataItem *metadataItem in array)
                {
                    //Handling TimedMetadata
                    [self handleTimedMetadata: metadataItem];
                }
            }
            
        }
    }

     
- (void)handleTimedMetadata:(AVMetadataItem *)timedMetadata
{
    // We expect the content to contain plists encoded as timed metadata
    // AVPlayer turns these into NSDictionaries
    
    id extraAttributeType = [timedMetadata extraAttributes];
    NSString *extraString = nil;
    if ([extraAttributeType isKindOfClass:[NSDictionary class]])
    {
        extraString = [extraAttributeType valueForKey:@"info"];
    }
    else if ([extraAttributeType isKindOfClass:[NSString class]])
    {
        extraString = extraAttributeType;
    }
    
    NSString *key = [NSString stringWithFormat:@"%@", [timedMetadata key]];
    
    //If tag starts with "www.nielsen.com", then only sending to SDK
    if ([key isEqualToString:@"PRIV"] && [extraString rangeOfString:@"www.nielsen.com"].length > 0)
    {
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [nielsenApi sendID3:extraString];
        });
    }
}


Life cycle of SDK instance

Life cycle of SDK instance includes four general states:

  1. Initial state – The SDK is not initialized and hence, not ready to process playing information. Once the SDK is moved out of this state, it needs instantiation of the new SDK instance in order to get the instance in the Initial state.
  2. Idle state – The SDK is initialized and is ready to process playing information. Once Initialized, the SDK instance is not processing any data, but is listening for the play event to occur.
  3. Processing state – The SDK instance is processing playing information. 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. stop – Call this API when the playback is paused, switches between content and ad (within the same content playback) or encounters interruptions.
    2. end – SDK instance exits from Processing state when this API is called.
  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 set to true (This is testing purposes only. Not for User Opt-Out.)

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.

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 (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 immediately (except when content is buffering) and withhold sending playhead position.
  • Call play once the playback resumes.

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

Going Live

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

  1. Debug Logging: Disable logging by deleting {nol_sdkDebug: 'DEBUG'} from initialization call.

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.

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 is contained in the ZIP package.

Testing an Implementation - App

See Digital Measurement Testing.