Google Analytics

Google Analytics SDK for iOS v1 (Legacy)

The Google Analytics for Mobile Apps SDK for iOS makes it easy to implement Google Analytics in an iOS-based applications. This document describes how to integrate the SDK with your apps.

  1. SDK Overview
  2. Getting Started
  1. Using the SDK
    1. Samples and Best Practices
    2. EasyTracker Library
    3. Starting the Tracker
    4. Tracking Pageviews and Events
    5. Tracking Ecommerce
    6. Using Custom Variables
    7. Anonymize IP
    8. Setting Sample Rate
    9. Batching Hits
    10. Known Issues
  1. Tracking Campaigns
    1. General Campaign Tracking

SDK Overview

This SDK uses a tracking model that is designed to track users to traditional websites and interaction with widgets in traditional web pages. For this reason, the terms used below reflect the conventional website tracking model and are being mapped over to tracking mobile applications. You should be familiar with Analytics tracking in order to understand how this SDK works.

Use the mobile tracking SDK to track your phone applications with the following Analytics interaction types:

Pageview Tracking
A pageview is a standard means to measure traffic volume to a traditional website. Because mobile apps don't contain HTML pages, you must decide when (and how often) to trigger a pageview request. Also, since pageview requests are designed to report on directory structures, you should provide descriptive names for the requests to take advantage of page path naming in the Content reports in Analytics. The names you choose will be populated in your Analytics reports as page paths even though they are not actually HTML pages, but you can use this to your advantage by structuring paths to provide additional groupings for your calls.
Event Tracking
In Analytics, events are designed to track user interaction to web page elements distinctly from pageview requests. You can use the Event Tracking feature of Google Analytics to make additional calls that will be reported in the Event Tracking section of the Analytics report interface. Events are grouped using categories and may also use per-event labels, which provides flexibility in reporting. For example, a multimedia app could could have play/stop/pause actions for its video category and assign a label for each video name. The Google Analytics reports would then aggregate events for all events tagged with the video category. For more information on Event Tracking, see the Event Tracking Guide
Ecommerce Tracking
Use the Ecommerce tracking feature to track shopping cart transactions and in-app purchases. To track a transaction, call the addTransaction method to create an overall transaction as well as the addItem method for each product in the shopping basket. Once collected, the data can then be viewed in the Ecommerce reporting section of the Google Analytics interface. For more information on Ecommerce Tracking, see the Ecommerce Tracking Guide.
Custom Variables
Custom variables are name-value pair tags that you can insert in your tracking code in order to refine Google Analytics tracking. For more information on how you can use custom variables, read the Custom Variable Guide.
NoThumb Support
The SDK for the iPhone now comes with a NoThumb version of the Library as well as the standard Thumb version. To use the NoThumb version of the Library, use the file libGoogleAnalytics_NoThumb.a instead of the file libGoogleAnalytics.a.

Getting Started

Requirements

To integrate Google Analytics' tracking capabilities with your iOS app, you will need the following:

Setup

  • Open Xcode and create a new iPhone OS project.
  • Drag GANTracker.h and libGoogleAnalytics.a from the SDK's Library directory into your new project.
  • Include the CFNetwork framework in your project and link against libsqlite3.0.dylib.

The Google Analytics for Mobile Apps SDK should work with any iPhone or iPod Touch running iOS 2.0 or higher -- the library is compatible with all iOS versions that support native applications.

An example application is included with the SDK that demonstrates what your project should look like if set up successfully. Feel free to use it as a template for your own Analytics-integrated apps.

Using the SDK

Before you begin using the SDK, you must first create a free account at www.google.com/analytics and create a new web property in that account using a fake but descriptive website URL (e.g. http://mymobileapp.mywebsite.com). Once you create the property, write down or keep a copy of the web property ID that is generated for the newly-created property.

A Web property ID is also known as the UA number of your tracking code and looks like UA-xxxxx-yy, where the x's and y's indicate the unique numbers for your view (profile). You must indicate the web property ID you'd like to use when instantiating the tracking object. See Web Property for more information.

You must indicate to your users, either in the application itself or in your terms of service, that you reserve the right to anonymously track and report a user's activity inside of your app. Your use of the Google Analytics SDK is additionally governed by the Google Analytics Terms of Service, which you must agree to when signing up for an account.

Samples and Best Practices

You can find sample code and best practices at code.google.com under the project analytics-api-samples.

EasyTracker Library

An EasyTracker Library is available. It provides application and UIViewController level tracking with almost no development effort. You can find it in the Downloads section of the analytics-api-samples project.

Starting the Tracker

Start the tracker by calling the startTrackerWithAccountID method on the tracker singleton obtained via [GANTracker sharedTracker]. It is often convenient to call this method directly in the applicationDidFinishLaunching method of your app's delegate. Pass the web property ID, required dispatch period, and optional delegate. For example:

#import "BasicExampleAppDelegate.h"

#import "GANTracker.h"

// Dispatch period in seconds
static const NSInteger kGANDispatchPeriodSec = 10;

@implementation BasicExampleAppDelegate

@synthesize window = window_;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
  // **************************************************************************
  // PLEASE REPLACE WITH YOUR ACCOUNT DETAILS.
  // **************************************************************************
  [[GANTracker sharedTracker] startTrackerWithAccountID:@"UA-0000000-1"
                                        dispatchPeriod:kGANDispatchPeriodSec
                                              delegate:nil];

  NSError *error;
  if (![[GANTracker sharedTracker] setCustomVariableAtIndex:1
                                                       name:@"iPhone1"
                                                      value:@"iv1"
                                                  withError:&error]) {
    // Handle error here
  }

  if (![[GANTracker sharedTracker] trackEvent:@"my_category"
                                       action:@"my_action"
                                        label:@"my_label"
                                        value:-1
                                   withError:&error]) {
    // Handle error here
  }

  if (![[GANTracker sharedTracker] trackPageview:@"/app_entry_point"
                                   withError:&error]) {
    // Handle error here
  }

  [window_ makeKeyAndVisible];
}

- (void)dealloc {
  [[GANTracker sharedTracker] stopTracker];
  [window_ release];
  [super dealloc];
}

@end

Tracking Pageviews and Events

Tracking pageviews and events is straightforward: simply call trackPageView of the tracker object each time you wish to trigger a pageview. Call trackEvent to record an event. For more on pageviews and events, see SDK Overview above.

Using Custom Variables

Adding a custom variable is also straightforward: just use the setCustomVariableAtIndex method provided by the mobile SDK. You'll want to plan out ahead of time which indexes each custom variable maps to, so you don't overwrite any previously existing variable. For more information on custom variables, see the Custom Variable Guide. Note that the method setCustomVariableAtIndex does not directly send data on its own. Rather the data is sent with the next tracked pageview or event. You have to call setCustomVariableAtIndex before you track a pageview or event. Note that the default scope of Custom Variables is page scoped.

Using Ecommerce Tracking

There are 4 methods you use to enable Ecommerce tracking in your application:

  • addTransaction
  • addItem
  • trackTransactions
  • clearTransactions

Calling addTransaction and addItem adds the transaction or item to an internal Ecommerce buffer, to which more items and transactions can be added. Only when calling trackTransactions will the transactions and items be sent to the dispatcher and get queued to be sent to Google Analytics.

To clear the buffer, you can call the clearTransactions method. Note: it does not recall any transactions previously sent to the dispatcher nor any transactions already collected by Google Analytics.

The following sample code can get you started.

  /**
   * The purchase was processed.  We will track the transaction and its associated line items
   * now, but only if the purchase has been confirmed.
   */
- (void) processPurchase:Purchase purchase {
  [[GANTracker sharedTracker] addTransaction:[purchase transactionId]
                                  totalPrice:[purchase totalPrice]
                                   storeName:[purchase store]
                                    totalTax:[purchase tax]
                                shippingCost:[purchase shipping]
                                   withError:&error];
  if (error) {
    // Handle error
  }
  for (PurchaseItem item in [purchase items]) {
    [[GANTracker sharedTracker] addItem:[purchase transactionId]
                                itemSKU:[item itemSKU]
                              itemPrice:[item price]
                              itemCount:[item count]
                           itemCategory:[item category]
                              withError:&error];
    if (error) {
      // Handle error
    }
  }

  if ([purchase isConfirmed]) {
    [[GANTracker sharedTracker] trackTransactions:&error];
  } else {
    // The purchase was denied or failed in some way.  We need to clear out
    // any data we've already put in the Ecommerce buffer.
    [[GANTracker sharedTracker] clearTransactions:&error];
  }
}

For more information on Ecommerce, see Ecommerce Tracking Guide.

Anonymize IP

To anonymize user IP information, set the property anonymizeIp to YES. This tells Google Analytics to anonymize the information sent by the SDK by removing the last octet of the IP address prior to its storage.

Here is an example of how to set it:

 [[GANTracker sharedTracker] setAnonymizeIp:YES];

You can set anonymizeIp at any time.

Setting Sample Rate

You can set the sample rate using the property sampleRate. If your application generates a lot of Analytics traffic, setting the sample rate may prevent your reports from being generated using sampled data. Sampling occurs consistently across unique users, so there is integrity in trending and reporting when sample rate is enabled. The sampleRate parameter is an NSUInteger and can have value between 0 and 100, inclusive. Here is an example that turns the sampleRate down to 95%:

 [[GANTracker sharedTracker] setSampleRate:95];

A rate of 0 turns off hit generation, while a rate of 100 sends all data to Google Analytics. It's best to set sampleRate prior to calling any tracking methods.

You can learn more about sampling from the Sampling Concepts Guide.

Batching Hits

To save on connection and battery overhead, we recommend batching your tracking requests. You can call dispatch on the tracking object any time you want to make a batch request, and you can do this either manually or at specific time intervals.

Tip: Bundle your tracker dispatches with other HTTP requests made by your application to reduce overhead.

Known Issues

  • Referrals/Traffic Sources: it is not currently possible to trace the campaign/referral source of an app download on the iOS device.
  • We strongly discourage calling dispatch in the following situations:
    • In the applicationWillTerminate method
    • In the applicationDidEnterBackground
    • Prior to calling stopTracker
    Doing so can result in hits being sent twice. Instead, use the dispatchSynchronous: method.
  • Calling GANTracker methods on different threads can result in obscure SQLite errors. Be sure to make all your calls from the same thread.
  • Tracking Campaigns

    General Campaign Tracking

    Note: Campaigns operate differently than conventional session-level referrals. The campaign remains valid for the life of a given application, unless overwritten by a later campaign.

    With version 1.3 of the Google Analytics SDK for iOS, you can now track campaign referrals. For example, if your application implements a Custom URL Scheme, you can create a URL that contains campaign query parameters. When your application launches in response to such a URL, you can retrieve the query parameters and pass them to setReferrer so that the information is stored in Google Analytics.

    To set the campaign referral information, use the setReferrer method like so:

      [[GANTracker sharedTracker] setReferrer:referrer withError:&error];
    

    There are two restrictions to using this feature. First, you must call startTrackerWithAccountID prior to calling setReferrer. You need to do this because the SQLite database used by Google Analytics isn’t set up prior to calling startTrackerWithAccountID and setReferrer needs that database. If you haven’t called startTrackerWithAccountID, you’ll get an error returned.

    The second restriction is that the referral string passed into setReferrer needs to follow a specific format. It must take the form of a set of URL parameters and must include at least a gclid parameter or one each of utm_campaign, utm_medium and utm_source. In the latter case, it can have utm_term and utm_content parameters as well.

    The gclid parameter is part of the autotagging feature that automatically links Google Analytics to AdWords. A sample campaign referral using autotagging might look like:

    referrer = @“gclid=gclidValue”;
    

    The manual campaign referral string might look like:

    referrer = @“utm_campaign=campaign&utm_source=source&utm_medium=medium&utm_term=term&utm_content=content”;
    

    If you pass in a badly formed referrer string to setReferrer, the referrer information will not be changed and you’ll get a return value of false. A return value of true indicates that the referrer was updated and will be added to every hit going forward. You'll also get an error returned that you can inspect to get details on what went wrong in the case that the call failed.

    Also note that a new session will be started when you call setReferrer and it returns true.

    Note: Setting the referrer records a new session for the subsequent hit. For a detailed description of each parameter, see the table below.

    Parameter Required Description Example(s)
    utm_campaign Yes Campaign name; used for keyword analysis to identify a specific product promotion or strategic campaign utm_campaign=spring_sale
    utm_source Yes Campaign source; used to identify a search engine, newsletter, or other source utm_source=google
    utm_medium Yes Campaign medium; used to identify a medium such as email or cost-per-click (cpc) utm_medium=cpc
    utm_term No Campaign term; used with paid search to supply the keywords for ads utm_term=running+shoes
    utm_content No Campaign content; used for A/B testing and content-targeted ads to differentiate ads or links that point to the same URL utm_content=logolink
    utm_content=textlink

    Authentication required

    You need to be signed in with Google+ to do that.

    Signing you in...

    Google Developers needs your permission to do that.