Introduction

The deltaDNA SDK for iOS allows your native iOS games to send information on in-game events and player actions to deltaDNA.

Events are sent to the deltaDNA platform as JSON objects, these events are managed and tracked using the online dashboard.

When your game triggers events the SDK will store them locally and upload them at regular intervals when a connection is available, or at a time of your choosing. This allows the SDK to collect events regardless of connectivity and gives you control over the timing and frequency of uploads.

Events vary in complexity, but are all derived from a common event schema. This document and the accompanying example application provide examples of a variety of events.

The source code for the SDK, written in Objective-C, is available on Github here.

Download the latest DeltaDNA SDK for iOS:

Important Changes:

Version 4.0.0 is a major update to the SDK and there are several changes that will require refactoring if you are updating from an earlier SDK version. V4.1.0 introduces some further refinements and additions. Previous versions of the SDK and release notes are available on the Release Notes page.

Importing the SDK

In order to import the SDK into your project you can use our CocoaPods project.

First you will need to make sure you have pods installed, this can be done with the following command:

$ sudo gem install cocoapods

The next step is to create a Podfile in your Xcode project folder, to do this navigate into your project and execute the following command:

$ pod init

This will create a file called Podfile, in the podfile you can define libraries you want to include in your project and sources for these libraries. To add the deltaDNA sdk make sure to include the underlined lines

Now the Podfile knows what frameworks/libraries you’d like to have in your project. To install them you run  the following command within your project:

$ pod install

See https://cocoapods.org for more information on CocoaPods.

Starting the SDK

The SDK needs to be started before you can send events from your game.

Add the following import statements.

Startup Parameters

You will need to supply at least three parameters to when you start the SDK. These parameters can be found on your “Game Details” page.

iOS-environment-variables

  • environmentKey : This is a unique 32 character string assigned to your application. You will be assigned separate application keys for development and production builds of your game.
  • collectURL :  This is the address of the server that will be collecting your events.
  • engageURL : This is the address of the server that will provide real-time A/B Testing and Targeting. This is only required if your game uses these features.
  • userID (optional) : Every user needs to have a unique userID. If your game can provide a unique userID you can use it. Alternatively, the platform will generate a unique User Id if none is provided and use it for all subsequent events. To generate a unique userID,just leave out the userID parameter the first time the SDK is started

These parameters above can be found on your game details page. Please note, there are different environmentKey parameters for your DEV & LIVE environments, you will need to change the environment key that you start the SDK with as you move from development and testing to production.

This is the minimum amount of code required to start the iOS SDK and send events. It will automatically send the newPlayer event the first time the SDK is run and the gameStarted and clientDevice event each time the game runs. Read on to find out how to go beyond recording a few automated events and start unlocking the power of deltaDNA with additional events, parameters, your own custom events, A/B tests and targeted campaigns.

Please ensure you run the deltaDNA SDK on the main thread of your App

Anatomy of an event

All events are recorded as JSON documents with a shared basic schema . The document will be different for every event type, but all of them should adhere to the following minimal schema:

The iOS SDK will automatically populate the userID, sessionID, eventTimestamp , platform & sdkVersion parameters for every event you send. When you add additional parameters to an event they should be placed inside the eventParams object.

The order of the parameters in your JSON event doesn’t matter.

You can inspect the parameters that each event expects, their type and any formatting or enumeration rules in the Event Manager.

Parameters can be either Optional or Required. Any parameters that are optional don’t have to be included in your event if you don’t have a valid value to put in them. It is better to leave them out completely, than set their value to null or empty.

This basic event structure provides great flexibility for recording events with varying levels of complexity, from simple events like the one above to complex events containing nested arrays. The following code examples will show a variety of events from simple to complex.

Please note that all events are validated and will be rejected if they don’t match the schema in the Event Manager.

Settings

The simple startup code above, is the minimum code required to start collecting analytics data from your players. You will quickly want to start adding more events and fine tuning your implementation. Be sure to check further down this page for a full list of settings, methods and helpers. In the meantime, here are a couple of useful things that you should do before the call to start.

  • Set the clientVersion  of your game. This is advisable and can be very useful for identifying behavioural differences between players on different builds of your game. SDK settings can be set before the SDK is started.
  • You might want to change session timeout setting with the setSessionTimeoutSeconds  method to suit your game.
  •  Detailed debugging is enabled by default in the pod file.
    There are many other useful settings described later that will help you with automated event collection, caching and communications, be sure to check them out.

Example 1 – A simple event.

The start up code that we have seen already will send the newPlayer, clientDevice and gameStarted events to deltaDNA automatically. In the following code we will add an event ourselves in code.

When we added our game to deltaDNA seven events were automatically added, these events tend to be standard across all games and are used to drive many of the dashboards. For now we will just use one of those standard events.

The following JSON event would be uploaded

Example 2 – Adding a new template event

The previous example used one of our seven standard events, this time we will do something a bit more ambitious, we will add an event to our schema from the predefined list of template events, add an additional custom parameter then trigger the event from our code.

Add a missionStarted event to your event schema from the event template list, then add a new missionDifficulty parameter of type STRING.

The code to trigger the missonStarted event using an Event helper.

The following JSON event would be uploaded

Pasting an event JSON into the Interactive Validator in the EVENTS menu can help resolve errors, our missionStarted event passed validation first time.

Example 3 – A complex event

The previous examples have been pretty straightforward and haven’t required much explanation. However, the following one is a bit more complex as it introduces nesting, arrays and some special objects that you will encounter when the player buys, trades, wins, exchanges currency and items with the game or other players. The good news is, the structure for this is fairly standard and the following event is as complex as it gets.

We are going to trigger a transaction event that records the player using some real world currency to purchase to purchase a treasure chest containing some virtual currency and multiple items. We will also take advantage of deltaDNA revenue validation with the Apple store to check that the transaction is valid.

As you can see the structure of the transaction event is a bit more complex. It contains a couple of Product objects for recording productsSpent and productsReceived.

Our JSON event will end up looking like

and the following code is required to create it.

The transaction event above was created using the Transaction helper class. It is also worth noting that the currency value is always sent as an integer in the minor currency unit and the realCurrencyType is an ISO-4217, 3 character currency code.

The above snippet is $4.99 USD.

 

Transaction Validation

The platform can undertake transaction receipt validation with the Apple Store in order to ensure that any revenue displayed in your dashboards is genuine revenue and not the result of a hacked game or Jail broken device.

If you wish to use revenue validation you will need to add a couple of details to the “Edit Game Details” page that can be reached from the “Manage Games” link on the left of the Welcome Screen.
e.g. for Apple you would set your 9 digit Apple StoreID. e.g. 971883677 and the URL to the Apple Receipt Validation service https://buy.itunes.apple.com/verifyReceipt

You also need to send three parameters along with each transaction event to tell deltaDNA that the transaction should be validated.

e.g. To validate an Apple store IAP

The transactionReceipt is the BASE 64 encoded receipt data that was returned from Apple. Please refer to the Apple developer website for details on Apple Receipt Validation

deltaDNA will then validate your revenue and add an additional revenueValidated parameter, containing the following potential values, to your transaction event.

  • 0 – no validation performed
  • 1 – revenue passed validation check
  • 2 – revenue failed validation check
  • 3 – revenue validation attempted, but result unknown (validation service may have been unavailable)

Transactions that fail validation with status code 2 or 3 will be excluded from your Measure Revenue charts and user metrics.

Since sandbox transactions do not actually generate revenue these are not shown by default in the revenue charts but if you would like to have these show up you can choose the sandbox URL on the”Edit Game Details” page (https://sandbox.itunes.apple.com/verifyReceipt), use 0 as the Apple StoreID and omit sending the transactionID since this is not part of the sandbox receipt. We strongly advice to do a final test with an actual transaction against the Apple Store since only such a transaction has all fields correctly set up.

There is a webinar and accompanying powerpoint presentation covering revenue validation in more detail on the Webinars page.

Example 4 – Engage

Games can retrieve time sensitive information from Engage to determine if a particular action should be taken for the user at a specific time, based on A/B Test results and Campaigns. Essentially your game should make Engage requests at predetermined decision points in your game and the response will allow you to personalise the gameplay for that user instantly.

The following example shows how you can use Engage targeting to change an IAP offer made to the player :

A targeted campaign would be setup on the deltaDNA platform to target specific users and inform the game of any parameters that should be modified or messages that should be presented.
The game can then:

  1. Make an Engage request
  2. And react to the response in a callback.

The code to make the Engage request looks like

This will create an Engage request containing the following JSON document and send it to Engage.

Engage will process your request very quickly, typically around 10ms, but the duration of the round trip will be dependent on network latency. Therefore, your game should be structured in such a way that is won’t stall if the user is on a high latency connection.

The engage response contains a transactionID and a parameters object containing any parameters relevant to this player at this point in time.

If the device doesn’t have internet connectivity at the time of the Engage request a cached response from the last successful Engage request for the same decision point will be contained in the response. The isCachedResponse parameter will indicate that this is a cached response.

You may receive a response containing a transactionID but no parameters with personalisation values. This indicates that the player has failed to meet any qualification criteria or has been allocated to a control group.

If there was an error processing your request, Engage will respond with the following error codes.

  • 400 – inputs malformed or incorrect in some way, or you are sending real-time parameters that haven’t been added to your Game Parameter list.
  • 403 – secret hash key incorrect or Engage is not enabled on your account.
    Please check that you have the “On-Demand” package enabled on your Game -> Packages page, you may need to get the Account Owner for your deltaDNA account to do this for you.
  • 404 – incorrect URL or unknown environmentKey

Image Messaging

Engage Actions can also deliver image based messages to your game at run-time and display popup messages. Each action is designed as part a campaign and is sent to a selection of users. The iOS SDK has an ImageMessage  class that draws the image message over your game. The popup is event driven so you are able to control when the image is downloaded from our servers, when it is presented to the player and the actions that should be taken if the player taps any of the buttons or dismisses the image message.

Each message consists of two parts, a sprite map that contains images for the background and a number of buttons, and a layout describing how to display these parts. The layout uses constraints to workout how to scale and where to place the popup. This means we don’t have to worry about screen sizes, but we can also protect parts of the screen from being covered up. The image is drawn as large as possible within those constraints whilst still maintaining the original aspect
ratio.

An Image Messaging Engage Request is the same as any other A/B Test or Campaign Request

The Engage response contains all the information for the ImageMessage class to render your image and buttons. Each button, and the background image can have an action that can be read in the response delegate. The action type can be nonedismisslink or action.
If the type is link or action a value field will provide a string value in the response delegate. If it is a link, then the browser is opened automatically by the SDK.

Image Message Class

To use an ImageMessage in your game, you should first create an Engagement object.

Then make your Engage request with the Engagement object and specify the response handler.

You can then build an ImageMessage object from the Engage response and fetch the assets for the Image Message

Then you can use a delegate to display the Image Message once the assets have been fetched

Further delegates can be used to react to the player clicking buttons or dismissing the Image Message.

Image Messages can also be used in conjunction with SmartAds to target Rewarded Video Ads to specific player segments. With all your targeting and segmentation decisions controlled in the deltaDNA campaign tools.

rewardedAdImageMessage

 

Apple Push Notification

The deltaDNA SDK for iOS can store the Apple Push Notification Token for the device and send it to deltaDNA so that you may send push notification messages to players. Your application will be responsible for retrieving (or refreshing) the push token from Apple and storing it in the SDK, thankfully this is very straightforward.

To request a push notification token you will need to add some code to your AppDelegate.m file,

To request the token from Apple.

To handle the token returned from Apple and send it to deltaDNA

and to handle situations where Apple fails to register the app for notifications

 

The token will then be sent to deltaDNA in a notificationServices event the next time events are uploaded. Please note if you renew the push notification you will need to call the set PushNotificationToken property to update the stored token.

You will also need to upload your iOS Certificate to the deltaDNA platform in order for Apple to accept push notification requests from deltaDNA, you can do this in the STEUP >> TOOLS – NOTIFICATIONS >> Manage Identity section of Dashboards. Your certificate from Apple needs to contain both your certificate and key and be saved as a .p12 file.CertificateIcon

Check out our Apple Certificate Guide, for more information on how to provision your App to receive Push Notification Messages, create a certificate and save the it in the correct format.

Recording Push Notification Events

When your app receives a push notification you can send an event back to deltaDNA so you can include it in your analysis and track open rates. The   recordPushNotification method can be called when:

The app is launched directly from the push notification.

or if the app is already running.

NB : It is safe to call the  recordPushNotification method before the SDK has been started.

Push Notification DeepLinking

Simple push notification messages are just used to prompt the player to open your app, however you can build more sophisticated behaviours by passing information in the notification payload that your app can react to. This is often used to gift the player with an in-game resource if they open the app, or guide them to a particular page within the app.

To implement deeplinking on iOS you need to:

  1. Send parameters in the payload of your notification for the app to react to.
  2. Build the hooks in to your app to react to parameters received in the notification payload
  3. Record an event to track Notification open rate

The following example gifts the player a power-up as an incentive for opening the app.

1) Adding Key Value parameters to the notification payload

Payload parameters are added at the bottom of the iOS page when you create a new notification on the Notifications Manager. ENGAGE -> NOTIFICATIONS -> CREATE A NOTIFICATION

parameters2

You can add as many Key/Value pairs to the notification payload as you want, but the entire push notification message cannot exceed 2048 bytes.

notification

2) Reacting to payload parameters inside the app.

You will need to add some code to the  application:didFinishLaunchingWithOptions  method in “Application Delegate” file to capture the parameters from the  launchOptions

If the app was launched from the push notification

If the app is already running when the notification is received.

 3) Record an event to track the notification open rate

Push Notification delivery is not guaranteed by Apple, they describe it as “best effort” so you will want to track which players open them. You should therefore record an event when the app is opened with a notification. You can also pass some parameters back in the event that will let you identify the precise notification and any payload parameters that were used.

You can use any event for this, we have created a notificationOpened event for this example and populated it with the notification message and payload parameters so we can track its effectiveness. This event can also be used to build player segments to re-target players for follow on notifications.

So for our application launch code might get extended a bit like:

Which would result in the following event being recorded.

Apple Identifiers

If you wish to record the Apple VendorID or Advertising Identifier parameters from a device you are responsible for retrieving them from the device and sending them as custom parameters with any events you wish to attach them to. You will also need to add these custom parameters in the event management tool.

NB: As of February 2014 Apple have started rejecting Apps that collect the advertising Identifier parameter but don’t display Ads.

Appendix 1 – Class Reference

DDNASDK

 Properties

  • settings
    The settings object lets you modify default SDK settings. Please see the settings reference below for more info.
  • hashSecret
    The hashSecret property should be set if you want your App to use hashing when validating your events.
  • clientVersion
    This property should be set by your App in order to differentiate between players using different builds of your game. The SDK will log a warning message if you don’t populate this property.
  • pushNotificationToken
    This property should be set before starting the SDK if you intend to send push notification messages to the device from the deltaDNA platform. Once set, the pushNotificationToken will be passed to deltaDNA with each gameStarted event. Your app will be responsible for requesting a push notification token from Apple.
  • environmentKey
    This read only property returns the environment key that the SDK is using in communications with deltaDNA. You have two environment keys, a DEV key and a LIVE key. These keys are used to keep your development and testing data separate from your live production data. This property should be provided to the SDK as a parameter in the SDK start method.
  • collectURL
    This read only property returns the URL that the SDK is using to send events to deltaDNA. This property should be provided to the SDK as a parameter in the SDK start method.
  • engageURL
    This read only property returns the URL that the SDK is using to make Engage targeting and A/B testing requests. This property should be provided to the SDK as a parameter in the SDK start method.
  • userID
    This read only property can be used to retrieve the userID from the SDK. The userID will either have been generated automatically by the SDK or provided by the client app when the SDK was started.
  • sessionID
    This read only property returns the sessionID the SDK is currently using. The SDK generates a new sessionID each time it is started.
  • platform
    This read only property returns the platform the game is being played on. This is automatically populated by the SDK.
  • isInitialised
    This read only property returns a Boolean value indicating if the SDK has been initialised.

Methods

  • start
    Starts the deltaDNA SDK. Requires three mandatory parameters (environmentID, collectURL, engageURL) that can be found on your game details page on the deltaDNA portal, please see the image below. The fourth, optional, userID parameter will be used if you provide it. If you don’t provide a userID the SDK will generate a unique anonymous userID for you and use it on all subsequent events.
    The parameters you need to provide in the start method can be found on your game details page in the deltaDNA portal.
  • stop
    Sends a gameEnded event and disabled background uploading of events.
  • newSession
    Changes the sessionID for the current user. This can be useful if your app has resumed from the background after a prolonged period.
  • recordEvent
    The recordEvent method creates a JSON event and stores it locally on the device. The SDK will upload all stored events at regular intervals or when the upload method is called. The recordEvent method expects you to provide an eventName and you can optionally provide additional parameters. The event schema for each event your game supports can be viewed and edited in the Event Management tool on deltaDNA. Rigorous validation is carried out on your events to prevent any errors corrupting your production data, you should refer to the schema for each of your events and use the QA tools when instrumenting your game.Each event you record will contain a bunch of parameters. An event is just a JSON object, you can attach these parameters to an event as an NSDictionary or you can use a deltaDNA EventBuilder helper object. There are overloaded triggerEvent methods for each.
  • upload
    The SDK will automatically upload any locally stored events at regular 1 minute intervals. If you wish to override this behaviour you can use the upload method to send events at a time of your choosing. You may wish to do this if your App is very resource intensive and you wish to send events when there is a lull in the action.
  • clearPersistentData
    Clears all locally stored data including userID, pushNotificationToken, clientVersion and any events that haven’t yet been uploaded from the client.
    [sdk clearPersistentData ];
  • recordPushNotification
    Sends a notificationOpened event to deltaDNA so that the open rate of notifications can be recorded and analysed. The didLaunch flag should be set to true if the notification was used to open the app or false if the app was already running.
     

DDNASettings

The settings object can be used to modify settings that control automated SDK features and communications.

  • onFirstRunSendNewPlayerEvent
    The SDK will automatically send a newPlayer event the first time it is run. Defaults to true. Set this to false if you want to override this behaviour and trigger your own newPlayer event with additional parameters.
  • onStartSendClientDeviceEvent
    The SDK will automatically send a clientDevice event each time your app is launched. The parameters within the clientDevice event are automatically populated by the SDK. Defaults to true. Set this to false if you want to override this behaviour and trigger your own clientDevice event with additional parameters.
  • onStartSendGameStartedEvent
    The SDK will automatically send a gameStarted event each time the app is launched. Defaults to true. Set this to false if you want to override this behaviour and trigger your own gameStarted event with additional parameters.
  • httpRequestRetryDelaySeconds
    The number of seconds the SDK should wait between failed upload attempts. Defaults to 2 seconds.
  • httpRequestMaxTries
    The number of retries that should be attempted for a failed upload attempt. Defaults to 5.
  • httpRequestTimeoutSeconds
    The number of seconds the SDK should wait before timing out an upload request. Defaults to 20 seconds.
  • backgroundEventUpload
    The SDK will automatically upload events at regular intervals if this property is set to true. Defaults to true. Set this property to false if you wish to control the timing of upload requests yourself. You may wish to do this if your game is particularly resource intensive and you wish to limit your uploads to periods when the game isn’t in a time critical section, e.g. on gameStart, in menus or after missions have been completed. If you are controlling the upload yourself please be aware that any events not uploaded in the current session will be uploaded in the next game play session when you call the upload method, however, if the player doesn’t play the game for a long time the events will be very out of date by the time they are uploaded and will be rejected by the event validator as a result.
  • backgroundEventUploadStartDelaySeconds
    The delay in seconds after the SDK is started until it attempts to upload events. Defaults to 0 seconds to ensure that any events stored from previous sessions are uploaded immediately.
  • backgroundEventUploadRepeatRateSeconds
    The number of seconds between automated event upload attempts.

DDNAEvent

The Event object helps you create structured events.

  • eventWithName
    Instantiates an Event object with the specified eventName.
  • setParam
    Adds a parameter to the event object
  • dictionary
    Returns an NSDictionary  of the Event object.

DDNAProduct

The Product object provides you with methods to help you build product objects as used in transactions and events that contain rewards.

  • init
    Initialises the Product Builder object
  • dictionary
    Returns an NSDictionary representation of the Products
  • setRealCurrency
    Adds a Real Currency object to the product
    NB: A product builder can only contain one Real Currency Object. The RealCurrencyType should be an ISO 4217 3 character currency code. The currency amount should be an integer of the smallest currency unit. Therefore the following code snippet equates to $4.99 USD
  • addVirtualCurrency
    Adds a virtual currency item to the product builder. You can add multiple virtual currencies to a product builder, they will be placed in an array of VirtualCurrencies.
  • addItem
    Adds an item to the product builder. You can add multiple items to a product builder, they will be placed in an array of items.