tvOS SDK

Setup

Download & Installation

Github Repository

Use the download button below to download SDK files from Github.

These files contain both a static library and a framework. Use one of these depending on the project.

Static files

These 2 files are placed inside the Library folder. Add them to your Xcode project and select to ‘copy the files’ into your project.

  • GameAnalytics.h
    Required header file containing methods for GameAnalytics.
  • libGameAnalyticsTVOS.a
    Required static library for GameAnalytics.

Framework

The framework is called GameAnalytics.framework. Add this to your project. When using a Framework it is needed to use the following when importing GameAnalytics.

CocoaPods Installation

Find our registered pod here.
If you have not used pods before, then it is recommended to go to cocoapods.org and read more about it.

Our CocoaPod will install the Framework version of the SDK.

Update your Podfile (in your project directory) with this information using your project name and the current SDK version released.

Run this command from the terminal in the Podfile folder.

In Xcode open the .workspace file generated by the pod installation and use that going forward.

ℹ️ When installing through CocoaPods you should not have to add dependency Frameworks/libraries manually.

tvOS Limitations

tvOS does not have a persistent reliable local storage like on iOS devices. This affects how the SDK will behave compared to iOS.

Key / Value storage

The iOS SDK will store certain key/values across sessions using a local database. As this cannot be done on tvOS the SDK is using the NSUserDefaults. The following fields are used when needed.

  • ga_tvos_dimension01
  • ga_tvos_dimension02
  • ga_tvos_dimension03
  • ga_tvos_gender
  • ga_tvos_fb
  • ga_tvos_birthyear
  • ga_tvos_session_num
  • ga_tvos_transaction_num

Event queuing

The SDK will queue events in a memory database (instead of a file on iOS) and send these periodically in a low priority thread.

If the device is offline it will gather these events in memory until a connection is established. If the device does not come online before the app is stopped then these events will be lost.

As most AppleTV will be fixed at either being offline or online it should work fine.

Progression event attempt counts

It is not possible to count unique progression attempts on tvOS due to the limitations on local storage and the nature of NSUserDefaults. This will result in Level Attempts metrics being displayed inaccurately in our tool.

Configure Xcode

To use the SDK in Xcode it is needed to add both the SDK library and it’s dependencies. In the “Build Phases” section add the following to “Link Binary With Libraries”.

  • AdSupport.framework
  • SystemConfiguration.framework
  • libsqlite3.tbd
  • libz.tbd
  • libGameAnalyticsTVOS.a

Using Swift?

To use the SDK in a Swift project it is needed to add a bridging header. But don’t worry – this is very easy.

Create a header file called GameAnalytics-Bridging-Header.h and add this line.

In the Build Settings for the Xcode Swift project locate the section called “Swift Compiler – code generation” and the field “Objective-C Bridging Header“. Add a link to the GameAnalytics-Bridging-Header.h file. It should now work in Swift throughout the project.

Now you are ready to write some code!

Initialize SDK

Using the SDK

Now we are ready for adding code to activate the SDK! Be aware of the following 3 phases:

  1. configuration
  2. initialization
  3. adding events or changing dimensions

The configuration and initialization steps should be called inside the common iOS method applicationDidFinishLaunchingWithOptions located in the AppDelegate class.

Once step 1 & 2 is done you can add events at different parts of the game code where some relevant action is happening.

Remember to import the GameAnalytics.h file whenever you need to call the SDK.

Configuration

The configuration phase happens before initialisation is called. The available configuration options are listed here.

  • build
  • user id
  • available (allowed) custom dimensions
  • available (allowed) resource currencies
  • available (allowed) resource item types

Build

Build is used to specify the current version of your game. Specify it using a string. Recommended to use a 3 digit version like [major].[minor].[patch]

User ID

The SDK will automatically generate a user id and this is perfectly fine for almost all cases. Sometimes it is useful to supply this user_id manually – for example if you download raw data for processing and need to match your internal user id (could be a database index on your user table) to the data collected through GameAnalytics.

Note that if you introduce this into a game that is already deployed (using the automatic id) it will start counting existing users as new users and your metrics will be affected. Use this from the start of the app lifetime.

Specifying allowed values

For certain types it is required to define a whitelist containing possible unique values during the configuration phase. When the SDK is being used (after initialisation) only the specified values will be allowed. 20 values are allowed for each list.

ℹ️ Processing many unique dimension values can be taxing for our servers. A few games with a poor implementation can seriously increase our cost and affect stability. Games will be blocked if they submit too many unique dimension values. We have this configuration requirement to guide users into planning what dimension values can be used.

ℹ️ Each resource currency string should only contain [A-Za-z] characters.

Initializing

Call this method to initialize using the game key and game secret for your game.

ℹ️ Don’t have any keys yet? Head over here and register your game at the GameAnalytics website!

Below is common example of the code placed in the AppDelegate class.

Adding Events

About Events

GameAnalytics feature the following event types.

Event Description
Business In-App Purchases supporting receipt validation on GA servers.
Resource Managing the flow of virtual currencies – like gems or lives.
Progression Level attempts with Start, Fail & Complete event.
Error Submit exception stack traces or custom error messages.
Design Submit custom event id’s. Useful for tracking metrics specifically needed for your game.

⚠️
Event id’s are strings separated by colons defining an event hierarchy – like kill:large.
It is important to not generate an excessive amount of unique nodes possible in the event hierarchy tree.
A bad implementation example.

[level_name]:[weapon_used]:[damage_done]

level_name could be 100 values, weapon_used could be 300 values and damage_done could be 1-5000 perhaps. This will generate an event hierarchy with:

100 * 300 * 5000 = 150M possible nodes.

This is far too many. Also the damage should be put as a value and not in the event string. The processing will perhaps be blocked for a game doing this and cause other problems when browsing our tool.

The maximum amount of unique nodes generated should be around 10k.

ℹ️ Please read our event guide here. You will get the most benefit of GameAnalytics when understanding what and how to track.

Business

Business events are used to track in-game transactions using real money.

ℹ️ Mobile games are often hacked and distributed illegally. Hacking an app will often involve faking/simulating all purchase requests. This will result in several Business events being sent to GameAnalytics for transactions that never occurred.

GameAnalytics provide the option of receipt validation for each purchase sent to GA servers. This process can ensure that revenue numbers reflect the actual spending in your game.

⚠️ Some configuration is needed before receipt validation will be active. Read information about validation and requirements for different platforms here.

Business event with receipt

When an in-app purchase is completed call the following method.

Field Type Description Example
currency string Currency code in ISO 4217 format.http://openexchangerates.org/currencies.json USD
amount integer Amount in cents. 99 is 0.99$
itemType string The type / category of the item. GoldPacks
itemId string Specific item bought. 1000GoldPack
cartType string The game location of the purchase.Max 10 unique values. EndOfLevel
receipt base64 string The transaction receipt. Nil allowed. nil

If the receipt is nil (or is an invalid receipt) then the GA servers will register that amount as not validated.

In iOS objective-c you can get the receipt string in base64 encoding like this.

Business event with auto fetch receipt

Using an alternative method it is possible to let the SDK retrieve the receipt automatically when called directly after a successful in-app purchase. The code performed by the SDK is identical (almost) to the objective-c example above.

Price (cents) and the currency ISO 4217 format

The amount is an integer with the price cent value. Basically this means multiplying the retrieved price with 100. Also the currency has to conform to the ISO 4217 format.

In Objective-C you implement IAP using the SKProduct classes. When initializing you would call the initWithProductIdentifiers method using the SKProductsRequest and get a list of products (valid and invalid). Also when completing the actual purchase you should have the SKProduct object.

?It is possible to use code frameworks that handle IAP flow (like soom.la) and thereby get this information from that code. Make sure the price is in cents and that the currency strings are returned as required.

The code below demonstrates how to get price (cents) and currency from an SKProduct object called skProduct.

ℹ️ For more information regarding business events go here.

Resource

Resource events are used to register the flow of your in-game economy (virtual currencies) – the sink (subtract) and the source (add) for each virtual currency.

ℹ️ Before calling the resource event it is needed to specify what discrete values can be used for currencies and item types in the configuration phase.

Source (add) Gem currency from an in-app purchase.

Sink (subtract) Gem currency to buy an item.

Sink (subtract) Gem currency to source (buy) some amount of another virtual currency (BeamBooster).

Sink (subtract) 3 BeamBooster currency that were used during a level.

Field Type Description Example
flowType enum A defined enum for sourcing and sinking resources. GAResourceFlowTypeSink
currency string The resource type/currency to track. Has to be one of the configured available resource currencies.This string can only contain [A-Za-z] characters. Gems, BeamBoosters, Coins
amount float Amount sourced or sinked. 0 or negative numbers are not allowed. 100.0
itemType string For sink events it can describe an item category you are buying (Weapons) or a place (Gameplay) the currency was consumed. For source events it can describe how the currency was gained. For example “IAP” (for in-app purchase) or from using another currency (Gems). Has to be one of the configured available itemTypes. Weapons, IAP, Gameplay, Boosters
itemId string For sink events it can describe the specific item (SwordOfFire) gained. If consumed during Gameplay you can simply use “Consumed”. For source events it describes how the player got the added currency. This could be buying a pack (BoosterPack5) or earned through Gameplay when completing a level (LevelEnd). BoosterPack5, SwordOfFire, LevelEnd, Coins400

⚠️ Be careful to not call the resource event too often !

In a game where the user collect coins fairly fast you should not call a Source event on each pickup. Instead you should count the coins and send a single Source event when the user either complete or fail the level.

ℹ️ For more information on the resource event go here .

Progression

Progression events are used to track attempts at completing some part of a game (level, area). A defined area follow a 3 tier hierarchy structure (could be world:stage:level) to indicate what part of the game the player is trying to complete.

When a player is starting a progression attempt a start event should be added. When the player then finishes the attempt a fail or complete event should be added along with a score if needed.

Add a progression start event.

Add a progression complete event with or without score.

It is not required to use all 3 if your game does not have them.

  • progression01
  • progression01 and progression02
  • progression01 and progression02 and progression03
Field Type Description Example
progressionStatus enum Status of added progression GAProgressionStatusStart GAProgressionStatusFail GAProgressionStatusComplete
progression01 string Required progression location. World01
progression02 string Not required. Use if needed. Stage01
progression03 string Not required. Use if needed. Level01
score integer An optional score when a user completes or fails a progression attempt. 1023

? Note that counting progression attempts is not working in the tvOS SDK. This is due to how local storage is handled. Read more here.

ℹ️ For more information on the progression event go here.

Error

Error Events

Used to track custom error events in the game. You can group the events by severity level and attach a message. To add a custom error event call the following function:

Field Type Description Example
severity enum Severity of error GAErrorSeverityDebug GAErrorSeverityInfo GAErrorSeverityWarning GAErrorSeverityError GAErrorSeverityCritical
message string Error message (can be nil) “Error when entering level12”

ℹ️ For more information on the error event go here.

Design Event

Every game is special. Therefore some needed events might not be covered by our [other event types](About Events). The design event is available for you to add your own event ID hierarchy.

ℹ️ Please note that custom dimensions and progression filters will not be added on design and error events. Therefore you cannot (at the moment) filter by these when viewing design or error metrics.

To add a design event call the following method.

It is also possible to add a float value to the event.

Field Type Description Example
eventId string The eventId is a hierarchy string that can consist of 1-5 segments separated by ‘:’. Each segment can have a max length of 32. The parts can be written only with a-zA-Z0-9 characters. “StartGame:ClassLevel1_5”, “StartGame:ClassLevel6_10”
value float A float event tied to the eventId. Will result in sum & mean values being available. 34.5

⚠️ It is important to not generate an excessive amount of unique nodes possible in the event hierarchy tree.

A bad implementation example.
[level_name]:[weapon_used]:[damage_done]

level_name could be 100 values, weapon_used could be 300 values and damage_done could be 1-5000 perhaps. This will generate an event hierarchy with:

100 * 300 * 5000 = 1.5M possible nodes.

This is far too many. Also the damage should be put as a value and not in the event string. The processing will perhaps be blocked for a game doing this and cause other problems when browsing our tool.

The maximum amount of unique nodes generated should be around 10k.

ℹ️ For more information on the design event go here.

Custom Dimensions

Using Custom Dimensions

GameAnalytics support the use of 3 custom dimensions.

  • Custom01
  • Custom02
  • Custom03

During the game it is possible to set the active value for each custom dimension dynamically. Once a dimension is set it will be persisted across sessions/game-start and automatically be added to these event categories.

  • Business
  • Resource
  • Progression

Setting each custom dimension.

Field Type Description Example
customDimension string One of the available dimension values set in the configuration phase. Will persist cross session. Set to nil to reset. ninja

ℹ️ Read more about custom dimensions here.

Demographics

User Information

During the game it is possible to set information about your users that will then be annotated to all other events.

  • gender
  • Facebook ID
  • birth year (age)

ℹ️ These user values will persist cross session/game-launch. Set them to nil to reset.

Set gender.

Set birth year.

Set Facebook ID.

Field Type Description Example
gender string Gender of player. female, male
birthYear integer The year the player was born. 1980
facebookId string Facebook Id of the player. 123456789012345

Debug & Verify

Debugging

The SDK is designed to be as silent as possible and use very few resources. You will therefore not get much information by default in the Xcode console.

We have 2 different debug log types that can be enabled / disabled (at any time).

  • info log
  • verbose log

Info log

Short messages will be output when enabled explaining when some action is being performed by the SDK. Sometimes cropping text / values to make it more readable.

Enable info log when implementing the SDK – remember to turn it off in production!

Verbose Log

Console output when each event is added (all fields) in JSON string format. This is the data being submitted to the GA servers for each event.

Enable verbose log when troubleshooting events.

This can result in a lot of text. When troubleshooting/debugging events it is therefore recommended to enable/disable when performing the action that need inspection.

Troubleshooting example.

Verify Implementation

Enable the Info Log to verify that events are being sent from your game project without any issues being reported.

Events submitted should register after a minor delay in our realtime dashboard in the GameAnalytics tool.

Read more about the realtime dashboard and our data processing.

How does it work?

Session Handling

Sessions are the concept of a user spending focused time on your game – from game start to the user leaving the game.

On iOS a new session will start once the game is launched (or when the app is “going to foreground”). A session will end once the game is “going to background”.

Session start

  1. Generate new session.
  2. Add a session start event (“user” event).
  3. Start the periodic activation of submitting queued events.
  4. Next event submit will fix potential missing session_end from earlier sessions.

Session end

  1. Stop the periodic activation of submitting queued events.
  2. Add a session_end event.
  3. Run a background task to submit queued events.

⚠️ If you are deploying testflight builds then please note that user id’s are handled a bit differently. The testflight environment is lacking any useful identifiers (they are random each app launch). The SDK will create a random user_id internally and use it for each app launch. If the game is removed and installed again, then a new user_id will be created though and it will register as a new user. Once it is deployed to the app store (or run locally on an actual device) it will track users (returning etc.) correctly.

Event Queue

Whenever an event is added (and validated) it will be added to a local database queue.

Interval

Every 15 seconds the SDK will start a task for submitting queued events since last submit. This processing is done in a separate low-priority thread that will have minimum impact on performance. The payload is gzipped and will therefore only consume a small amount of bandwidth.

Offline

When a device is offline the events are still added to the queue. When the device is online it will submit.

Thread Handling

For the iOS platform almost every piece of the SDK code is run using a dedicated low-priority serial thread queue to avoid UI lag or sudden performance spikes.

The queue will execute each task sequentially. If the SDK add several tasks to the queue then each will have to wait until it’s turn. A task could be adding an event or submitting queued events.

Consider this example with 3 calls.

The configureBuild is required to be called before initialize is completely finished. The design event call is required after initialize is finished. The queuing will make sure that each task is completely finished before proceeding to the next one.

There is more!

There is much more to GameAnalytics and we suggest that you read our general documentation.

Please create a support ticket if you have any feedback like..

  • bugs
  • confusing features or UI
  • great ideas!

We hope you enjoy our service!