Google Analytics for iOS

Learn how to add usage tracking and other metrics into your iOS app with this Google Analytics Tutorial for iOS! By .

Login to leave a rating/review
Save for later

Learn how to add usage tracking and other metrics into your iOS app with this Google Analytics Tutorial for iOS!

Learn how to use Google Analytics

Learn how to use Google Analytics for iOS7!

To build successful products, you and your team have to become a lean, mean, measuring machine! Otherwise, you’ll have little way of knowing which parts of your app are consistently used and in working order.

There are many ways to measure usage and many off-the-shelf frameworks that can help. In this tutorial, you’re going to look at using Google Analytics for iOS.

This tutorial will take you through the major components of the Google Analytics SDK. Along the way, you will add Google Analytics to a timer app suitable for runners, and put the SDK to work tracking how frequently people use the various features and controls.

When you are finished you will have enabled app screen and event tracking, you will be able to track app versions usage, and will allow the app users to opt-out of the anonymous usage tracking if they wish so:

Opt Out

Take your position at the starting line. Get ready… get set… BOOM! GO, GO, GO!

Getting Started: What is Google Analytics?

Google Analytics is a service offered by Google that generates detailed statistics about your website or mobile app’s usage. Originally, the product was aimed at marketers rather than developers. However, modern development methodologies require developers to define, measure and test the features they create in an iterative, low-cost way. Google Analytics is a great tool for measuring your app’s usage to test if new features are working both functionally and experientially.

Google Analytics provides you with high-level, dashboard-type data for an overview of your app’s performance, along with more in-depth reporting tools. Its analysis can identify such things as poorly performing screens, important user events and the geographical distribution of your user-base… all of which are critical to improving your app!

With a quick glimpse at the Google Analytics Dashboard you can see how many unique users your app had last month, what percentage of them used it more than once, how long did they use your app in a single session, which country your users came from and more:


By tracking events in your app like users pressing various buttons or performing different actions you can have insights on whether one or other feature is more used and plan how to develop your app further. For example on the report below you can clearly see that users prefer saving photos to their device (2,223 times last month) vs. sharing straight to Facebook (113 times) and posting to Twitter (33 times):


Lap 1: Setting Up Google Analytics for Your App

Okay, that might have felt like a false start, but now you are off and running. Go to The homepage should appear like so:

1 Sign In

Note: If you do not have a Google account, you will need to create one now by selecting Create an Account on the top-right side of the page. For the remainder of this tutorial we are going to assume you have create your own Google Analytics account.

Once you have logged in, you simply need to click the Access Google Analytics button on the top right.

Google Analytics Existing Users

The first screen you see lists all of your accounts. If you have clients, typically you will have one account set up for each. If you are new to Google Analytics you will only have the first account you set up.

Google Analytics - Existing Accounts

Select the Admin view on the top right. To see the main dashboard area for managing your Accounts, Properties, and Views.

Google Analytic Dashboard

On the main dashboard you are presented with a workflow that starts with Account, progresses to Property and ends in View (Profile). Lets first break down what each of these sections refer to.

  • Account – It can seem confusing however, within your own Google Analytics Account you can be a member of multiple analytics accounts owned by clients or other collaborators. In the account drop down list on the right-hand column you will see a list of all of the accounts you are a member of.
  • Property – A property refers to a particular website or application that belongs to a given account. In this tutorial you will be creating a new Clock property to house all of the data associated with your app.
  • View – The final column is the view column. This enables you to create different views on your data. By creating different views on a single property (in this tutorial’s case an app) you are able to monitor data from different versions of your app which you will look at later on in the tutorial.

Ok lets go! Ensure that you have the correct Account selected for this project. You don’t want to add a new property to one of your clients’ accounts.

Select the Property drop-down and click on the Create new property item, like so:

Google Anaylitcs New Property

Google then asks you to submit the details for the app you want to track. Make sure to choose Mobile app at the top and enter the information as required. In the Setting up your property section, enter Clock for the App Name.

Google Analytics New Property

After accepting the terms of service, the website takes you to a page with your tracking ID and the download link for the SDK.

Downloading the Google Analytics iOS SDK

Before you do anything else, write down your app’s Tracking ID, which will be of the form ID UA-XXXXXXXX-Y. Keep the ID handy, because you will need it soon.

Now download the Google Analytics iOS SDK presented on the final summary page. Save this somewhere handy, such as your desktop, so you don’t have to rummage around trying to find it later. Download the version without Admob features.

Google Analytics ID & SDK

Lap 2: Setting Up the Google Analytics SDK

To begin this lap, please download the starter project.

Open the starter project in Xcode and build and run it in the Simulator to verify it is working. You should see a tab-bar-based app with a clock and a stopwatch.

Clock Starter Project Initial Screen

Unzip the Google Analytics SDK you downloaded when creating your tracking ID. You will see the following:

  • GoogleAnalytics
  • GoogleTagManager
  • libGoogleAnalyticsServices.a
  • Readme.txt

Inside the GoogleAnalytics folder, open the Library folder, select the following files and drag them into the Clock group within your starter project.

  • GAI.h
  • GAITracker.h
  • GAITrackedViewController.h
  • GAIDictionaryBuilder.h
  • GAIFields.h
  • GAILogger.h

Google Analytics Add Header Files

Be sure to select the checkboxes: Copy items into destination group’s folder and Add the files to the Clock target.

Now you need to add the Google Anayltics iOS SDK that is named libGoogleAnalyticsServices.a. The Google Analytics SDK also uses the CoreData and SystemConfiguration frameworks (at the moment you have to add these frameworks manually, in the next version hopefully Google will use automatic importing in the next version), so you need to add all of the following to the app’s libraries:

  • libGoogleAnalyticsServices.a
  • CoreData.framework
  • SystemConfiguration.framework
  • libz.dylib

Begin by selecting libGoogleAnalyticsServices.a and dragging it into your Frameworks folder. You can place it anywhere inside your project, but it’s best to keep all of your frameworks in one place.

Google Analytics Adding GA Lib

Next add the CoreData framework. Select the Clock project file in the Project Navigator and then select Build Phases. Expand the Link Binary With Libraries section and click the add (+) button.

Google Analytics Adding Libraries

In the pop-up window, type in CoreData to refine the search and select CoreData.framework from the filtered list.

Google Analytics Add Libraries

Repeat the previous steps to find and add both SystemConfiguration.framework and the libz.dylib library.

Finally, modify Clock-Prefix.pch to import the GAI.h header, as follows:

#import "GAI.h"
#import "GAIFields.h"

You’ve equipped your app with the SDK. Let’s get tracking!

Lap 3: Tracking

As you come around the first bend, you are ahead of all the other runners. Keep up the pace!


GAI (Google Analytics for iOS) is a top-level class that provides facilities to create trackers and set behavioural flags. This class provides access to a shared instance for convenience, in turn this exposes a default tracker instance. The default tracker is initialized to nil and is set by calling trackerWithTrackingId on the shared GAI instance. Should you wish to change this tracker you can override it as required, this is covered later.

The Google Analytics Tracker is used to track screens, events, transitions, timing, and exceptions. The implementation of this interface is thread-safe, and no calls are expected to block or take a long time. All network and disk activity will take place in the background.

So lets see the tracker in action!

Initializing the Tracker

You will need the tracking ID that you obtained in the first part of the tutorial. First you are going to get the Google Analytics for iOS shared instance and setup a number of behavioural flags along with the tracker. The specific behavioural flags you are going to set are:

  • trackUncaughtExceptions – Tracking uncaught exceptions will flag up any exceptions that you are not dealing with that have caused your application to crash.
  • logLevel – Google Analytics iOS SDK has 4 logging levels: kGAILogLevelError, kGAILogLevelWarning, kGAILogLevelInfo, and kGAILogLevelVerbose. Verbose logging enables all of the various types of log output and prints it to the console in Xcode. This is extremely useful when you first start using Google Analytics for iOS as it lets you see what is going on under the hood.
  • dispatchInterval – By default, this is set to 120, which states that tracking information should be dispatched (uploaded to Google Analytics) automatically every 120 seconds. In this tutorial you will set this to a shorter time period so that you can see the data in your Google Analytics dashboard without having to wait for a prolonged period of time. In a production environment every 120 seconds should be often enough.

To initialize the tracker in your GAI’s sharedInstance, open the app delegate and insert the following into application:didFinishLaunchingWithOptions:, using your own tracking ID in section 4:

// 1
[GAI sharedInstance].trackUncaughtExceptions = YES;

// 2
[[GAI sharedInstance].logger setLogLevel:kGAILogLevelVerbose];

// 3
[GAI sharedInstance].dispatchInterval = 20;

// 4
id<GAITracker> tracker = [[GAI sharedInstance] trackerWithTrackingId:@"UA-XXXXXXX-Y"];

This code will configure and get an instance of your tracker class, so you can start tracking app usage and app events.

Note: Remember to use the tracking ID you obtained when you set up Google Analytics for this app.

Automatic Screen Tracking

Google Analytics was originally built for websites, where it is used to measure pageviews—that is, instances in time where some user views a distinct page on a website. In Google Analytics for mobile, the analog to a webpage is a screen. This will usually represent a single screen of content in your app, but the term can also more generally describe any distinct piece of content your app presents, such as a single component within the screen.

Similarly, the analog to a pageview is a screen view, which represents the act of a user viewing that screen of your app. It’s easy to confuse this sense of “view” with the usual sense of the term in iOS development, where it means a visible UI component within an app rather than the act of a user looking at a part of the app. So stay on your toes when browsing the Google Analytics documentation.

Given all of this, automatic screen tracking means gauging how long users spend looking at the different screens of your app. When users navigate between screens, you will want to record those navigations events, along with the time spent on each screen. In iOS, every screen is managed by a view controller, so you record this information about a screen by updating its view controller.

You can do this automatically by extending GAITrackedViewController. The only manual step required is to set GAITrackedViewController‘s internal property, screenName, which defines the name of the screen for the analytics log.

Let’s use the automatic way to add analytics logging to the screen that displays a clock, which is handled by ClockViewController. First, update ClockViewController.h by importing GAITrackedViewController and extending it as follows:

#import "GAITrackedViewController.h"

@interface ClockViewController : GAITrackedViewController


Second, update ClockViewController.m to set the screenName property. It’s best to do this in viewDidLoad:

- (void)viewDidLoad
    [super viewDidLoad];
    self.screenName = @"Clock";

That’s it! These two small changes allow a lot of things under the hood to just work. Now that the view controller has a name for the associated screen this name will be used within the parent GAITrackedViewController viewWillAppear: method to register a screen view. Within this method a lot of things are at work the parent viewController will:

  1. Get the shared instances’ Default Tracker setup with your tracking ID.
  2. Tell the tracker that it’s tracking the “Clock” screen.
  3. Generate a logging entry containing the time and other information.
  4. Use the Default Tracker object to publish that to the Google Analytics servers for visual exploration. Since we have configured the logging level to output verbose logging you will also see this output to the console.

Not bad for just a couple of lines! Your app is already sending usage data to the Google Analytics servers, but hold your horses just a moment before heading to the GA Dashboard. Let’s add a bit more functionality before checking the results.

Manual Screen Tracking

While automatically recording screen views can be convenient, it is not always possible or desirable to extend the built-in GAITrackedViewController.

In this case, there is a manual approach. You can send information about a screen to Google by explicitly going through the steps that were performed above automatically. You need to get the tracker object, set the field values representing the screen on the tracker object, and then manually build and send the screen view event, or “hit.”

Let’s instrument the StopWatchViewController with this approach. Open StopWatchViewController.m and import GAIDictionaryBuilder at the top of the file:

#import GAIDictionaryBuilder.h

Unlike before, you have to get a handle to the default tracker and give it an identifier for the screen you are currently tracking. You then construct an app view record, that will cause the tracker to record the screen has been viewed and send that to your property on Google Analytics. In the same file, add viewDidAppear as follows:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
    [tracker set:kGAIScreenName value:@"Stopwatch"];
    [tracker send:[[GAIDictionaryBuilder createAppView] build]];

Build and run the app! Spend a few moments switching between the two tabs. Every time you switch tabs, you are viewing a new screen. This screen view produces a “hit” event, which the app logs out to the debug console as a timestamp and a dictionary of descriptive fields. You will see below our Stopwatch screen has been recorded with an appview event.

Verbose Console Showing Screen View

From time to time, the debug console will also show you calls to instances of GAIBatchingDispatcher. This is the Google Analytics library automatically sending the log messages to the Google Analytics web service. After you’ve seen those messages in the console, you should be able to see your activity on the Google Analytics website. If you navigate to the real-time area in your properties reporting dashboard you can see how many users are on each screen at any one time and how that changes in real-time.

Real-Time Screen Usage

Note: Pay attention to the date range you are previewing in Google Analytics, it does not include today by default and you will not see the hits you produce until you include today’s date in the range.

Google Analytics provides various views into your data. A good one to try is Standard Reports->Real-Time->Screens, which will show you screen transition events over the last few minutes.

Lap 4: Advanced Configuration

Now that you are on the home straight lets look at recording finer grained interactions such as button presses and the use of multiple trackers.

Setting and Sending Data

You can send specific data to Google Analytics if you want to record finer-grained user interactions. These can range from button presses to implicitly triggered events such as network calls. You can send this data by first setting maps of key-value pairs on the tracker and then sending them to Google using the methods set: and send:, respectively. You already saw an example of this in the previous section.

Recap: In viewDidAppear, you set the screenName and make a request to the tracker to send the information to Google Analytics.

id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
[tracker set:kGAIScreenName value:@"Stopwatch"];
[tracker send:[[GAIDictionaryBuilder createAppView] build]];

Applying Values to Multiple Measuring Events

To capture tap events, you can specify the kGAIHitType in the events parameters. Let’s add a method to log button presses on the Stopwatch screen. You will call this method in the IBActions associated with each of the Stopwatch buttons.

First, add this method to StopWatchViewController.m:

-(void)logButtonPress:(UIButton *)button{
     id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
    [tracker set:kGAIScreenName value:@"Stopwatch"];
    [tracker send:[[GAIDictionaryBuilder createEventWithCategory:@"UX"
                                                           label:[button.titleLabel text]
                                                           value:nil] build]];
    [tracker set:kGAIScreenName value:nil];

First you get a handle of the default tracker. As before, you need to set the current screenName on the tracker to ensure the button press is recorded for the correct screen.

However, you’re not recording the act of the user viewing the screen. So instead of sending a screen view, you create a touch event, which is categorized as a UX event in Google’s framework. You send the title of the button as the title of the event. Finally, you remove the screenName set on the tracker to prevent other events from being associated with the wrong screen.

In other words, the tracker object is not just a transparent conduit for passing messages. It carries state, which affects the messages you send. The only values that you should set directly on the tracker are those you want to persist across multiple hits.

Setting a screenName on a tracker makes sense, since you can apply the same value to subsequent screen views and event hits. However, I don’t recommend that you set a field like hit type on the tracker, because it will likely change with each hit.

Call this method in both the startToggle and reset methods to record when a user presses these buttons:

   [self logButtonPress:(UIButton *)sender];

   [self logButtonPress:(UIButton *)sender];

Build and run the app. Switch to the Stopwatch page, toggle the stopwatch on and off a few times and then hit the reset button to record some data.

To view this information, go back to Google Analytics and navigate to your app’s statistics. On the left side of the page, expand Behavior->Events->Overview and you will see the events you just initiated.

Google Analytics Events

Using Multiple Trackers

It is possible to use multiple trackers in your app. This can be useful for sending data to different Google Analytics properties associated with the same app. For example, maybe you have one property set up for your marketing team, who require information about how the app is being used, and another set up for your development team, who are looking at problem areas.

Note: In this tutorial you are not going to add multiple trackers to your example. This section just gives you an idea how to implement this in case you need multiple trackers.

Setting up multiple trackers is as simple as initializing trackers with different property IDs:

id<GA Tracker> tracker1 = [[GAI sharedInstance] trackerWithTrackingId:@"UA-XXXX-1"];

id<GAITracker> tracker2 = [[GAI sharedInstance] trackerWithName:@"Tracker2"

By default, the first tracker initialized becomes the default tracker made available through the GAI shared instance. You have seen how to access this perviously.

id<GA Tracker> tracker = [[GAI sharedInstance] defaultTracker];

If you consider the previous two code blocks together the tracker returned as the default tracker associated with GAI would refer to tracker1. If you want to change the default tracker you can override it like so:

[[GAI sharedInstance] setDefaultTracker:tracker2];

In this case every subsequent call to the default tracker will access tracker2.

Sampling Rate: Avoiding Inconsistencies

Sampling in Google Analytics or in any analytics software refers to the practice of selecting a subset of data from your data set and reporting on the trends available in that sample set. Sampling is widely used in statistical analysis because analyzing a subset of data gives similar results to analyzing all of the data. Sampling speeds up processing for reports when the volume of data is so large as to slow down report queries. This is important if your user-base is extremely large.

Earlier you covered three key terms, Accounts, Properties, and Views. When creating a view on a particular property (think of this as a window into your app’s usage from a given perspective) you must ensure that the data being sent has been sampled at the same rate. If this is not the case, data that is sampled at a higher frequency (events logged more often) will overshadow those sampled at a lower frequency (events logged less often) which can skew your analysis.

To ensure that your tracker is sampling data consistently you should maintain a constant sample rate for each version of the app you release. Updating the tracker with the current version number is easy: add the following code to your AppDelegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
    [tracker set:kGAIAppVersion value:version];
    [tracker set:kGAISampleRate value:@"50.0"];

This code will fetch the current app version from your Xcode Info.plist file automatically and set it to the tracker object. It then sets a 50% sampling rate.

Now change the version number of your app to 1.2 in the project settings.

Project Version Number Update

When you run the application the tracker will reflect this change and record all data with the correct version number. The final step is to create a view in Google Analytics to filter the data by version number.

Go back to your Google Analytics dashboard and on the right-hand view drop down choose create new view.

Create a new view on your dashboard

Be sure to to select mobile app and create a name for this new view, here I am using Clock – v1.2.

Complete the settings for the new view

This will successfully create a new view and as next step you have to set a filter to specify what data you want that view to show.

Successfully creating a view

Choose the filters option below the view drop down and choose new filter (red button that comes in).

New filter page

Apply the appropriate filter settings as shown below. You are filtering the data by app version and in this case you are only looking at data from version 1.2.

Filter Settings

Now Build and Run the iOS app and watch the data stream in on your newly created view by selecting Reporting->Real-Time->Screens

Real-time view

Opting Out

Last but not least: you can allow your users to opt-out of anonymous usage logging. You can enable an app-level opt-out that will disable Google Analytics across the entire app by setting an optOut property on the tracker object, like so:

[[GAI sharedInstance] setOptOut:YES];

For your clock app, you are going to ask users to opt in or out on launch. First we will create an alert view and show it inside the AppDelegate when the application finished launching. To correctly handle the alert view you must ensure your AppDelegate implements the UIAlertViewDelegate. In your app delegate, SSAppDelegate.h, add the following code:

#import <UIKit/UIKit.h>

@interface SSAppDelegate : UIResponder <UIApplicationDelegate, UIAlertViewDelegate>

@property (strong, nonatomic) UIWindow *window;


Then in your app delegates methods file SSAppDelegate.m add:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Google Analytics" message:@"With your permission usage information will be collected to improve the application." delegate:self cancelButtonTitle:@"Opt Out" otherButtonTitles:@"Opt In", nil];
    [av show];
    return YES;

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            [[GAI sharedInstance] setOptOut:YES];
        case 1:
            [[GAI sharedInstance] setOptOut:NO];

This will display the alert view once the application has finished launching giving the user two options:

  1. Opt into logging in which case you will see all of their data on Google Analytics
  2. Opt out of logging in which case nothing will be sent back

Build and run one last time. The app will present you with the choice of opting in or out of usage logging. Be sure not to stab yourself in the back by Opting out of usage tracking while still testing the clock app :]

Opt Out

Where to Go From Here?

You’ve crossed the finish line for this tutorial! I hope what you’ve learned will help you make best use of Google Analytics in your mobile apps. You can download the complete clock project here.

You can do much more once you have data coming in to your Google Analytics account:

  • Experiment with the reports provided for you – you can customize what data is plotted and create more complex reports by crossing a number of tracking parameters
  • Check out the report Behavior / Behaviour flow – it shows you the sequence of how “hits” happened. Effectively if you are conducting an A/B test for a given screen you can check whether the A or B case produces more conversions to your next screen
  • Let your imagination go wild – don’t consider Google Analytics to be just a business tool and try to figure out how it can be useful for you. For example if you are developing a quest game – let GA report every time your player finds an object in the game. This way you’ll figure out if some objects are too hard or too easy to discover on your map! Ka-jing!

If you have any questions, comments or suggestions, feel free to join the discussion below!