Category

Difference between revisions of "iOS SDK API Reference"

From Engineering Client Portal

(Event and Error Handling)
Line 423: Line 423:
 
*Method for users to opt-out of Nielsen measurement, any time while using the application
 
*Method for users to opt-out of Nielsen measurement, any time while using the application
  
== Event and Error Handling ==
 
 
== Event and Error Handling ==
 
== Event and Error Handling ==
 
=== Constants / Enumerations ===
 
=== Constants / Enumerations ===

Revision as of 01:42, 23 May 2017

Engineering Portal breadcrumbArrow.png Digital breadcrumbArrow.png iOS SDK API Reference

The iOS 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. These SDKs leverage the following:

  • Nielsen audio watermark technologies for TV audience measurement
  • The industry supported ID3 metadata tag specification
  • Nielsen Combined Beacon technology

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 (DTVR), Digital Content Ratings (DCR), Digital Ad Ratings (DAR), 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
  • Application crash events
  • Time of viewing a sub section / page in the application.

Initialization

The latest version of App SDK allows instantiating multiple instances of App SDK object and can be used simultaneously without any issues (The sharedInstance API that creates a singleton object in previous versions of App SDK is removed).

  • Maximum of four SDK instances per appid are supported in this release. When a fifth SDK instance is launched,

Stages of SDK Initialization

Step 1: App SDK Initialization

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.

Step 2: Setting up event and error notifications

Once the NielsenAppApi object has been initialized, the next step is to enable notifications regarding ID3 tags extracted from the playing stream. In case of standard AVFoundation player, the SDK NSNotificationCenter API is used to

  • Collect HLS timed metadata events (ID3 tags) during viewing sessions.
    • Set up a timed metadata event listener method for receiving ID3 tags and calling Nielsen sendID3.
  • SDK uses the following NielsenAppApiDelegate protocol methods to notify its delegate (set during initialization) about event / error information.
    • nielsenAppApi:eventOccurred
    • nielsenAppApi:errorOccurred

Note: Ensure to add to your view controller’s @interface.

(void)nielsenAppApi:(NielsenAppApi *)appApi eventOccurred:(NSDictionary *)event {NSLog(@"Sample player is Notified by a Event : %@", event);
}
(void)nielsenAppApi:(NielsenAppApi *)appApi errorOccurred:(NSDictionary *)error {NSLog(@"Sample player is Notified by an Error : %@", error);
}
Sample event confirmation to player application upon successful initialization of SDK
NielsenSDKSampleDebug[9028:237989] [Nls:0] -I- Analytics framework Status:
{
"Event Description" = "Nielsen App SDK Version, ai.4.0.0.4 is initialized by the Player…";
EventStatus = 2001;
TimeStamp = "2015-07-23 14:51:06 +0000";
}

Step 3: Nielsen App SDK Streaming Sessions

After setting up observers for SDK events/errors and a listener method to process incoming Nielsen ID3 tags, the next steps are to

  • Call play while starting or resuming a streaming session.
  • Load CMS metadata using loadMetadata.
  • During session play, call playheadPosition every one second until the stream is stopped or interrupted (due to ad breaks or buffering).
  • Call stop when pausing, ending a viewing session, or buffering is detected.

Serialized JSON string from NSDictionary

NSDictionary* appInformation = @
{
  @"appid": @"TXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
  @"appname": @"Sample App Name",
  @"appversion": @"2.0",
  @"sfcode": @"uat-cert",
  @"nol_devDebug": @"INFO"
}
NSData* jsonDataAppInfo = [NSJSONSerialization dataWithJSONObject:appInformation options:0 error:nil];
NSString *jsonAppInfoString = [[NSString alloc] initWithData:jsonDataAppInfo encoding:NSUTF8StringEncoding];
nlsAppApiMeter = [[NielsenAppApi alloc] initWithAppInfo:jsonAppInfoString delegate:self];

Nielsen App SDK object handles filtering of ID3 tags and CMS tags, queuing/buffering of data, and all communications with Nielsen collection facility.

For more information on handling the streaming sessions, refer to Nielsen Measurement Products.

Nielsen iOS App SDK Application Life Cycle

initialization appcycle.png

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. Call initWithAppInfo:delegate: to move into this state. 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. play and loadMetadata calls move the SDK instance into this state. In this state, the SDK instance will be able to process the following calls.
    1. playheadPosition – Call this API every one second when playhead position timer is fired.
    2. sendID3 – Call this API when ID3 tags are identified in the stream.
    3. stop – Call this API when the playback is paused, switches between content and ad (within the same content playback) or encounters interruptions.
    4. 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 called

Note: For API Version 5.1 and above, App SDK will fire data pings and continue measurement even after the user has opted out from Nielsen measurement on a device. The data ping will be marked as opted-out ping.

Note: In case of any interruptions during playback due to alarm, calendar, call, flight mode, Wi-Fi toggle, channel change, etc., call stop to stop the measurement.

Finite-state machine table

This table provides the possible changes of state for the SDK instance, when it is in a specific state and receives an API call.

API call received Initial State Idle State Processing State Disabled State
initWithAppInfo:delegate: IDLE STATE (OR)

DISABLED STATE

IDLE STATE - -
play & loadMetadata - PROCESSING

STATE

- -
playheadPosition - - PROCESSING

STATE

-
sendID3 - - PROCESSING

STATE

-
stop - - IDLE STATE -
end - - IDLE STATE -
appDisableApi: YES - DISABLED

STATE

- -
appDisableApi: NO - - - IDLE STATE (OR)

DISABLED STATE

userOptOut: YES - - IDLE STATE -
userOptOut: NO - PROCESSING

STATE

- -
'-' indicates that no API call is expected.

Handling JSON Metadata

All the SDK methods handles only two types of objects: NSString, NSDictionary. The parameters passed must be either a JSON formatted string or a NSDictionary object. The JSON passed in the SDK must be well-formed.

  • NSDictionary object
    • If an object of unexpected type is passed to the method, the error message will be logged.
    • If string has invalid JSON format, the error message will be logged.
  • JSON value must be string value.
    • This includes boolean and numeric values. For example, a value of true should be represented with "true", number value 123 should be "123".
    • All the Variable Names like appid, appname, sfcode, dataSrc, title, type etc. are case-sensitive. Use the correct variable name as specified in the documentation.
  • JSON string can be prepared using either raw NSString or serialized NSDictionary.

JSON for NSDictionary object

NSDictionary* appInformation = @{
                                  @"appid": @"TXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
                                  @"appname": @"Sample App Name",
                                  @"appversion": @"2.0",
                                  @"sfcode": @"uat-cert",
                                  @"nol_devDebug": @"INFO"
                                };
nlsAppApiMeter = [[NielsenAppApi alloc] initWithAppInfo:appInformation delegate:delegate];

appid, appname, and appversion are mandatory parameters while sfcode is optional. nol_devDebug is meant for creating logs in test environments only.

JSON string from raw NSString

NSString *appInfoString = @"{\"appid\" : \"TXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\", \"appname\" : \"Sample App Name\",\"appversion\" : \"2.0\",\"sfcode\" : \"uat-cert\"}";
NielsenAppAPi *appAPI = [[NielsenAppApi alloc] initWithAppInfo:appInfoString delegate:self];

JSON string from serialized NSDictionary

NSDictionary* appInformation = @
{
@"appid": @"appid",
@"appname": @"appname",
@"appversion": @"2.0",
@"sfcode": @"sfcode",
@"nol_devDebug": @"INFO"
};
nlsAppApiMeter = [[NielsenAppApi alloc] initWithAppInfo:appInformation delegate:self];

While using JSON format for sending metadat, ensure enough care in including special characters in the values for arguments.

Example

{
@"type": @"radio", // To send "radio" in metadata string
@"assetid": @"WXYZ-FM'101",
@"stationType": @"3",
@"provider": @"SampleProvider" // To send "SampleProvider" in metadata string
}

Note: For mandatory parameters like appid, appname, and appversion, please refer to the parameters table in initWithAppInfo:delegate:

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.

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

Examples of extracting ID3 tags from the iOS Native Player

AVPlayer

ID3 tags will be received in the Player on AVMetadataItem Callback method. Create & get the AVMetadataItem callback method

[self.player addObserver:self
        forKeyPath: kTimedMetadataKey
        options: NSKeyValueObservingOptionNew
        Context: MyStreamingMovieViewControllerTimedMetadataObserverContext];


 (void)observeValueForKeyPath:(NSString*) path
                      ofObject: (id)object
                        change: (NSDictionary*)change
                       context: (void*)context
{
/* Set the AVPlayerLayer on the view to allow the AVPlayer object to display
     its content. */
    //[playerLayerView.playerLayer setPlayer:player];
/* AVPlayerItem "status" property value observer. */
if (context == MyStreamingMovieViewControllerTimedMetadataObserverContext)
        {
            id newMetadataArray = [change objectForKey:NSKeyValueChangeNewKey];
            if (newMetadataArray != [NSNull null])
            {
                array = newMetadataArray;
                for (AVMetadataItem *metadataItem in array)
                  {
                    [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;
    }
  if ([(NSString *)[timedMetadata key] isEqualToString:@"PRIV"]&&[extraString rangeOfString:@"www.nielsen.com"].length> 0)
  {
   if ([[timedMetadata value] isKindOfClass:[NSData class]])
   {
            // Sending ID3 Tag
/* The  sendID3: sends the extracted Nielsen ID3 payload to the App SDK for analysis. */
            [[NielsenAppApi sharedInstance]sendID3: extraString];
            NSString *value=[timedMetadata stringValue];
            if (value != nil)
            {
               // NSString *strMessage=[[@"ID3 Tag Received " stringByAppendingFormat:@"%d\n",countForMetadata] stringByAppendingString:value];
                [self appendLogConsoleText:extraString];
            }
   }
  }
    else
    {
        NSLog(@"Could not send ID3 tags");
    }
    countForMetadata++;
    
}

Movie Player

ID3 tags will be received in the Player on MPTimedMetadata Callback method. Sample Implementation of MPTimedMetadata callback

 (void)handleTimedMetadata:(MPTimedMetadata*)timedMetadata
{
    id extraAttributeType = [timedMetadata  allMetadata];
    NSString * extraString= nil;
    if ([extraAttributeType isKindOfClass:[NSDictionary class]])
    {
        extraString = [extraAttributeType valueForKey:@"info"];
    }
    else if([extraAttributeType isKindOfClass:[NSString class]])
    {
        extraString = extraAttributeType;
    }
    
  if ([(NSString *)[timedMetadata key] isEqualToString:@"PRIV"]&&[extraString rangeOfString:@"www.nielsen.com"].length> 0)
    {
     if ([[timedMetadata value] isKindOfClass:[NSData class]])
      {
            // Sending ID3 Tag
            [[NielsenAppApi sharedInstance]sendID3: extraString];
            NSString *value=[timedMetadata value];
            if (value != nil)
            {
                
                [self appendLogConsoleText:extraString];
            }
      }
    }
    else
    {
        NSLog(@"Could not send ID3 tags");
    }
    countForMetadata++;
}

Note: ID3 tags are not applicable for International (Germany)


IOS SDK API Methods & Properties

Scenario Method / Property DTVR DAR Digital Audio DCR International (Germany) Description
Initialize initWithAppInfo:delegate: Used to create a new instance of the SDK object
Measurement play Used when there is an ID3 fed product such as DTVR and the client does not want to send in all the CMS metadata that is sent in loadMetadata. This allows the client to send in at least the required “channel name” value associated to the ID3 feed. If this is not called then the “channel name” value populated will be the default value of “defaultChannelName”.
Measurement loadMetadata Used to send ad or content metadata to the SDK in the form of JSON string. Application constructs a JSON hashmap and calls this API.
Measurement sendID3 Used to send the ID3 metadata.
Measurement playheadPosition Used to send the playhead position.
Measurement stop Used when playback is paused and when switching between ad and content or content and ad.
Measurement end Used when content playback is complete. This is triggered 1) at the end of the content stream, 2) if the user switches to another piece of content
Measurement updateOTT Used to notify App SDK that the remote OTT device (like Google ChromeCast, Roku, Amazon FireTV, etc.) is connected / disconnected (change of OTT status).
Opt-out optOutURL Used to fetch the Nielsen opt-out web page URL.
Opt-out userOptOut Used to supply the response message from opt-out webpage to the SDK.
Opt-out optOutStatus Call this API to retrieve the Opt-Out or Opt-In state.
Opt-out appDisableApi

(kill switch)

Used to disable the SDK.
Log lastErrorDict Returns SDK error in the form of dictionary if any error has occurred.
Log lastEventDict Returns SDK event in the form of dictionary if any event has occurred.
Log meterVersion Returns the current SDK version.
Log nielsenId Used to get a string defining the Nielsen ID (NUID) number for the device.
Log demographicId Used to retrieve Demographic ID (Device ID) of the current device.
Log debug Used to enable/disable debug flags. Newly introduced in SDK version 5.0.0 for International (Germany)

NielsenAppApi Class Description

The NielsenAppApi class is the primary application interface to the Nielsen App SDK. For example, after an instance object of the NielsenAppApi class is created and initialized, it can be used by the calling application to collect HLS timed metadata using the SDK’s sendID3: method. These are the public methods and properties exposed by the NielsenAppApi class:

@interface NielsenAppApi: NSObject

  @property (readonly) BOOL optOutStatus;
  @property (assign) BOOL appDisableApi;
  @property (assign) BOOL debug;
  @property (readonly) NSString *nielsenId;
  @property (readonly) NSString *demographicId;
  @property (readonly) NSString *optOutURL;
  @property (readonly) NSString *meterVersion;
  @property (readonly) NSDictionary *lastEventDict;
  @property (readonly) NSDictionary *lastErrorDict;

   (instancetype)initWithAppInfo:(id)appInfo delegate:(id)delegate;

   (void)play:(id)channelInfo;
   (void)loadMetadata:(id)metadata;
   (void)stop;
   (void)end;
   (void)playheadPosition:(long long)playheadPos;
   (void)sendID3:(NSString *)data;
   (void)updateOTT:(id)ottInfo;
   (BOOL)userOptOut:(NSString *)optOut;

   (NSString *)getNielsenId _attribute((deprecated((Please use nielsenId property instead.))));
   (NSString *)optOutURLString _attribute((deprecated((Please use optOutURL property instead.))));
   (NSString *)getMeterVersion _attribute((deprecated((Please use meterVersion property instead.))));
   (NSDictionary *)getLastEventDict _attribute((deprecated((Please use lastEventDict property instead.))));
   (NSDictionary *)getLastErrorDict _attribute((deprecated((Please use lastErrorDict property instead.))));

  @protocol NielsenAppApiDelegate<NSObject>

  @optional
   (void)nielsenAppApi:(NielsenAppApi *)appApi eventOccurred:(NSDictionary *)event;
   (void)nielsenAppApi:(NielsenAppApi *)appApi errorOccurred:(NSDictionary *)error;

@end

Nielsen Sample Applications

Nielsen iOS sample player application consists of two sample application based on native Players integrated with SDK framework. The player demonstrates all the supported functions of the SDK.

  • NielsenVideoPlayer
  • NielsenRadioPlayer

Implementation of Video and Audio sample apps is based on native iOS AVPlayer.

The UI components of the iOS App SDK sample applications are common to both as shown below.

  • From the Channel Selection buttons ⬇️ & ⬆️ , the user will be able select the channels to stream.
  • The Info button ℹ️ displays information of the SDK version, current Nielsen ID used for the device, and the option for opt-out/opt-in.
  • The Play ▶️ and Pause ⏸️ buttons will control the streaming of the selected channel.
  • The area at the bottom of the window displays the current stream status.
  • The Clear button 🔃 clears out the status window.
  • The Email button 📧 can be used to email the tags and status in a text file to Nielsen.

If target device supports Picture-in-Picture playing, it could be activated by PIP button in the Video player window.

  • Channel URLs and metadata are obtained from two locations:
    • Channels 1 and 2 are configured from the Settings application. Channel URLs and metadata parameters can be modified.
    • Channels starting from 3 are configured in specific JSON file. URLs to this JSON config file can be changed from the Settings application.

Nielsen Privacy Requirements

Privacy protections that Nielsen ensures to have with each App SDK integration are as follows.

  • Disclosure of viewership data collection in app store description
  • Disclosure of viewership data collection in EULA / Privacy Policy
  • A link in the EULA/Privacy policy, or in another conspicuous location within the App, to a Nielsen-hosted web page outlining what Nielsen is collecting and how it is being used
  • Method for users to opt-out of Nielsen measurement, any time while using the application

Event and Error Handling

Constants / Enumerations

The following are the details of Delegate Implementation:

-(void)nielsenAppApi:(NielsenAppApi *)appApi eventOccurred:(NSDictionary *)event
{
   NSLog(@"Sample player is Notified by a Event: %@", event);
}
    (void)nielsenAppApi:(NielsenAppApi *)appApi errorOccurred:(NSDictionary *)error
{
   NSLog(@"Sample player is Notified by an Error: %@", error);
}

AppApiEventCode

An enumeration with predefined App SDK event state transition codes.

typedef NS_ENUM(unsigned int, AppApiEventCode)
{
     AppApiStartup = 2001,
     AppApiShutdown = 2002,
}AppApiEventCode;

App SDK Event Codes

Event Code Event Name Event Description
2001 AppApiStartup App SDK has initialized successfully. It will happen only after App SDK has received a valid config file
2002 AppApiShutdown App SDK is shutting down. It will happen just before App SDK is destroyed

AppApiErrorCode

An enumeration with predefined error codes which the App SDK object can generate.

typedef NS_ENUM(unsigned int, AppApiErrorCode)
{
   AppApiNetworkConnectionFailure = 1001,
   AppApiFileWriteFailure = 1002,
   AppApiFileReadFailure = 1003,
   AppApiEmptyValue = 1004,
   AppApiEmptyAppName = 1005,
   AppApiEmptyAppVersion = 1006,
   AppApiEmptyAppId = 1007,
   AppApiAnExceptionOccured = 1008,
   AppApiUnknownExceptionOccured = 1009
};

App SDK Error Codes

Event Code Event Name Event Description
1001 AppApiNetworkConnectionFailure App SDK Could not connect to server
1002 AppApiFileWriteFailure App SDK Could not write to file
1003 AppApiFileReadFailure App SDK Could not read data from file
1004 AppApiEmptyValue Empty value Found.
1005 AppApiEmptyAppName Cannot initialize SDK Object without an AppName(Player Name)
1006 AppApiEmptyAppVersion Cannot initialize API Object without an AppVersion
1007 AppApiEmptyAppId Cannot initialize API Object without an AppId
1008 AppApiAnExceptionOccured Exception occurred
1009 AppApiUnknownExceptionOccured Unknown exception occurred