DTVR iOS SDK

From Engineering Client Portal

Engineering Portal breadcrumbArrow.png Digital breadcrumbArrow.png US DCR & DTVR breadcrumbArrow.png 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), and Digital Ad Ratings (DAR). Nielsen SDKs are also equipped to measure static content and can track key life cycle events of an application like:

  • Application launch events and how long app was running
  • Time of viewing a sub section / page in the application.

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 us to ensure accurate reporting.

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

Prerequisites

Before you start the integration, you will need:

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

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

Implementation

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

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

How to obtain the NielsenAppApi.Framework

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

Contents

Setting up your Development Environment

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

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

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

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

Configuring Xcode Development Environment

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

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

Special Note for Static Framework

Starting from 8.2.0.0 release framework is build from the mixed (swift + objc) source codse. If static (xc)framework is integrated additional settings should be applied to fix build or runtime issues.

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;

xCode 12 building errors

Developers who uses "fat" framework in their apps started reporting the following error that they get building the app in xCode 12.3+:

Building for iOS Simulator, but the linked and embedded framework 'MyFramework.framework' was built for iOS + iOS Simulator.

The binary framework contains different code for the same architecture in multiple places, and Xcode doesn’t know how to handle it. There is workaround that people recommend to use in such cases:

IPA processing failure

Assertion failed: Expected 4 archs in otool output:

The error above is due to the "fat" (simulator+device) framework which will not appear if you have not enabled Bitcode. To build your app with full Bitcode support, it is recommended that you use a XCFramework to avoid the 4 archs in otool output message.

SDK Initialization

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

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

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

Debug flag for development environment

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

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

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

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

Swift Example

Sample SDK Initialization Code

NielsenInit.swift

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


ViewController.swift

class ViewController: UIViewController, NielsenAppApiDelegate, AVPictureInPictureControllerDelegate, CLLocationManagerDelegate  {

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

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

Objective C

Sample SDK Initialization Code

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

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

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

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


The following would be the NlsAppApiFactory.h file:

#import <Foundation/Foundation.h>

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


The following might be in the Viewcontroller.m

@implementation ViewController

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


Initializing Viewability and Audibility Measurement

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

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

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

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

Calling trackViewability for player view

Input Parameters

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


Objective C

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


Swift

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


PlayerView FirendlyView(Timer & Slider).png

Data Collected

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

APP SDK Error & Event Codes

To view the Error and Event codes for iOS, 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
type type of asset "content"
adModel linear vs dynamic ad model 1 = Linear matches TV ad load
    
- (NSDictionary *)loadDtvr{
    
    //Loading DTVR data  
    NSDictionary *dtvr = @{ @"adModel":@"1" ,  
                            @"type":@"content",};  
    return dtvr;
}

SDK Events

Event Parameter Description
'loadMetadata' content/ad metadata object Needs to be called at the beginning of each asset to pass type and adModel.
'play' Call when starting or resuming a streaming session.

Note:no longer required for SDK version 7.2 or higher.

'stop' playhead position Call when content or ads complete playing and pass playhead position

Note:no longer required for SDK version 7.2 or higher.

'sendID3' Used to send the ID3 tag payload retrieved from the stream Needs to be called at the beginning of playback

Configure API calls - play

Call at start of new stream:

Swift

nielsenAppApi?.play();

Objective C

   [nielsenAppApi play:()];


Note: no longer required for SDK version 7.2 or higher.

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.

Swift

nielsenApi.stop()

Objective C

[nielsenApi stop];


Note: no longer required for SDK version 7.2 or higher.

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. For DTVR, the loadMetadata call moves 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.
  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, 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.

Sample Applications

The below sample applications have been designed to show the 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.