Home > Services & APIs

Analytics for iOS

Set Up Analytics

To use the Analytics service, your app must include the Amazon Insights SDK. The Insights SDK manages communication with the Amazon services used to set up and process Analytics.

Step 1: Set Up an Identifier on the Amazon Apps & Games Developer Portal

If you already have an Identifier, skip to Step 2.

If you do not yet have an Identifier to use with the Analytics Service, you can create one.

From the Analytics console, click Create Identifier.

Enter an identifier and click Save Identifier.


Step 2: Download the SDK

Download the SDK by clicking here.

Integrating the SDK

Step 3: Add Frameworks to Your Xcode Project

Add the Amazon Insights Framework to your Xcode project by going to your project settings and in the Summary tab, adding the AmazonInsightsSDK framework in the Linked Frameworks and Libraries section. You will also need to add the SystemConfiguration and CoreTelephony frameworks, and libz.dylib library, all of which come as part of the iOS default set of frameworks and libraries.

The Amazon Insights Framework and documentation are located in the Amazon Mobile App SDK download package in the folder /iOS/AmazonInsights/.


Step 4: Import the AIAmazonInsightsSDK Header

Add this import statement to the source or header files of the class(es) that need to use Amazon Insights:

#import <AmazonInsightsSDK/AmazonInsightsSDK.h>

Step 5: Initialize Amazon Insights SDK

Initialize the Amazon Insights SDK as shown here:

// The Identifier's Public Key acts as the application key.
id<AIInsightsCredentials> credentials = [AIAmazonInsights credentialsWithApplicationKey: @"YOUR_APP_KEY"
                                                                         withPrivateKey: @"YOUR_PRIVATE_KEY"];

AIAmazonInsights* insights = [AIAmazonInsights insightsWithCredentials: credentials];

Note: You must replace YOUR_APP_KEY and YOUR_PRIVATE_KEY with actual values.

Alternatively, you can initialize the SDK with additional options by using code similar to the following:

id<AIInsightsOptions> options = [AIAmazonInsights optionsWithAllowEventCollection:YES
                                                             withAllowWANDelivery:YES];

id<AIInsightsCredentials> credentials = [AIAmazonInsights credentialsWithApplicationKey: @"YOUR_APP_KEY"
                                                                         withPrivateKey: @"YOUR_PRIVATE_KEY"];

AIAmazonInsights* insights = [AIAmazonInsights insightsWithCredentials: credentials
                                                           withOptions: options];

If you do not specify an AIInsightsOptions object, the SDK initializes with Event Collection turned on and WAN Delivery disabled. See Submit Events to the Website on this page for more about delivery options.

You must maintain the reference to the Insights instance in your application. You may optionally request the Insights instance for your application each time you need to use it by requesting it via insightsWithCredentials: selector on the AIAmazonInsights class. That method will attempt to retrieve a previously initialized instance if it exists for the provided AIInsightsCredentials; otherwise, it will create a new instance. Subsequent requests for an Insights instance will always serve the same instance for the same AIInsightsCredentials.

AIAmazonInsights* insights = [AIAmazonInsights insightsWithCredentials: credentials];

(* assumes you already have a credentials object available.)


Step 6: Record Session Events

Recording session events enables the Analytics service to determine a number of metrics, including session counts, retention, and more. In the Amazon Insights SDK for iOS, session start and end events are automatically recorded for you. This is accomplished via a background and foreground listener being registered within the SDK that is triggered for these state transitions. The listener will record the appropriate events when necessary.


Step 7: Record Purchase Events

Recording purchase events enables the Analytics service to determine a number of metrics, such as Average Revenue Per Device (ARPD) and Conversion. Purchases should be recorded for every purchase made within your app using real currencies.

Real Currency Purchase

id<AIEventClient> eventClient = insights.eventClient;

// productCatalog is a NSMutableDictionary of SKProduct indexed by the productIdentifier
// (Can be implemented however needed)

// get the SKProduct for the product identifier that was purchased
SKProduct* product = [productCatalog objectForKey:transaction.payment.productIdentifier];

// create a builder that can record purchase events from Apple
AIAppleMonetizationEventBuilder* builder = [AIAppleMonetizationEventBuilder builderWithEventClient:eventClient];

// set the product id of the purchased item (obtained from the SKPurchaseTransaction object)
[builder withProductId:transaction.payment.productIdentifier];

// set the item price and price locale (obtained from the SKProduct object)
[builder withItemPrice:[product.price doubleValue] andPriceLocale:product.priceLocale];

// set the quantity of item(s) purchased (obtained from the SKPurchaseTransaction object)
[builder withQuantity:transaction.payment.quantity];

// set the transactionId of the transaction (obtained from the SKPurchaseTransaction object)
[builder withTransactionId:transaction.transactionIdentifier];

// build/record the monetization event
id<AIEvent> purchaseEvent  = [builder build];
[eventClient recordEvent:purchaseEvent];

Step 8: Record Custom Events

You can have up to 1,500 unique Custom Events per app, 20 Attributes per Custom Event, and an infinite number of Attribute values. There are no limits on the volume of Custom Events passed by your app to the Amazon Analytics service, and the service remains free at any level of use.

// Record when the user completes level 1
// Get the event client from Insights instance.
id<AIEventClient>  eventClient = insights.eventClient;

// Create a level completion event.
id<AIEvent>  level1Event = [eventClient createEventWithEventType:@"level1Complete"];

// add an attribute to know what weapon the user completed the level with
[level1Event addAttribute:@"sword" forKey:@"weaponUsed"];
// add a metric to know how many coins the user collected in the level
[level1Event addMetric:@105 forKey:@"coinsCollected"];

// add a metric to know how long it took the user to complete the level
[level1Event addMetric:@300 forKey:@"levelDuration"];

// Record the level completion event.
[eventClient recordEvent:level1Event];

Step 9: Submit Events to the Website

Events are automatically submitted to the server when the application is put into the background. You do not need to explicitly submit events with the Amazon Insights SDK for iOS. There is an explicit submitEvents selector exposed on the AIEventClient class that you can use to proactively attempt to submit the recorded events to the server. Only use this method if you need to send events to the server while your application is running.

To submit events to the server, use the submitEvents selector on the AIEventClient provided by the AIAmazonInsights instance.

                                    [eventClient submitEvents];

There is a throttle on how frequently you may invoke this selector and submit events. You can request a maximum of one submission per minute. If you try to perform a submission within one minute of a previous submission, the new submission request will be ignored.

Note: If you enabled WAN delivery when creating the AIAmazonInsights instance, the SDK will transmit all recorded events to the Website if the user has either a WAN or a Wi-Fi connection. If you did not enable WAN delivery, the SDK will transmit events only over Wi-Fi.


Complete Code Example

-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
   for (SKPaymentTransaction* transaction in transactions) {
      switch (transaction.transactionState) {
         case SKPaymentTransactionStatePurchased:
         // when an item is purchased, give the user access to the content, and
         // record a monetization purchase event.
         [self completeTransaction:transaction];
            break;
         case SKPaymentTransactionStateFailed:
            // ... handle a failed transaction
            break;
         case SKPaymentTransactionStateRestored:
            // ... restore the transaction
            break;
      }
   }
}


-(void)completeTransaction:(SKPaymentTransaction*)transaction{

   // The Identifier's Public Key acts as the application key.
   id<AIInsightsCredentials> credentials = [AIAmazonInsights credentialsWithApplicationKey: @"YOUR_APP_KEY"
                                                                            withPrivateKey: @"YOUR_PRIVATE_KEY"];
   AIAmazonInsights* insights = [AIAmazonInsights insightsWithCredentials: credentials];

   id<AIEventClient> eventClient = insights.eventClient;

   // productCatalog is a NSMutableDictionary of SKProduct indexed by the productIdentifier
   // (Can be implemented however needed)
   // get the SKProduct for the product identifier that was purchased
   SKProduct* product = [productCatalog objectForKey:transaction.payment.productIdentifier];

   // create a builder that can record purchase events from Apple
   AIAppleMonetizationEventBuilder* builder = [AIAppleMonetizationEventBuilder builderWithEventClient:eventClient];

   // set the product id of the purchased item (obtained from the SKPurchaseTransaction object)
   [builder withProductId:transaction.payment.productIdentifier];

   // set the item price and price locale (obtained from the SKProduct object)
   [builder withItemPrice:[product.price doubleValue] andPriceLocale:product.priceLocale];

   // set the quantity of item(s) purchased (obtained from the SKPurchaseTransaction object)
   [builder withQuantity:transaction.payment.quantity];

   // set the transactionId of the transaction (obtained from the SKPurchaseTransaction object)
   [builder withTransactionId:transaction.transactionIdentifier];

   // build/record the monetization event
   id<AIEvent> purchaseEvent  = [builder build];
   [eventClient recordEvent:purchaseEvent];

   // finalize the transaction as required by Apple
   [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

Note: You must replace YOUR_APP_KEY and YOUR_PRIVATE_KEY with actual values.

Debugging and Testing

Debugging Tools Setup

You will use logs to get debugging information from the SDK. The logs can be found in the output window within the debug area in Xcode. To avoid showing too many details we limit the display of event names in logs to the first five characters.


Log Messages

The following is a quick reference of log messages output by the SDK for debugging of functionality.

Verify Logging of Session Events

YYYY-MM-DD HH:mm:ss.zzz … Event: '_sess...' recorded to local filestore

Verify Logging of Monetization Events

YYYY-MM-DD HH:mm:ss.zzz … Event: '_mone...' recorded to local filestore

Submitting Events

Events are submitted automatically to the server when the application is put into the background. You do not need to explicitly submit events with the iOS SDK.

Successful submission of events will result in the following cat message:

YYYY-MM-DD HH:mm:ss.zzz … Successful submission of 5 events

Events are sent to the server only if an established Internet connection is available. Please ensure that your device is connected to the Internet and that your connection type is compatible with your initialization configuration.

Note: By default, Amazon Insights delivers only over Wi-Fi. To enable WAN delivery, set the WAN parameter to true on the AIInsightsOptions object.


Return to the Analytics product overview