How To Integrate Google Analytics Tracking Into Your Apps In 7 Minutes

April 22nd, 2010 Posted by: brandontreb - posted under:Snippets

Ok, maybe that title is +- 3 minutes depending on how efficient you are ;) .

What?

So, why would you want to integrate Google Analytics into your iPhone application.  Duh, for the same reasons you would integrate it into your site.  Google has extended their killer analytics platform to include mobile devices including the iPhone and Android devices.

The analytics API gives you some very powerful options to get as nitty gritty as you would like in your application tracking.

Why?

Uhh, because stats are freakin sweet.  Even if you don’t have a million+ downloads of your app, it is still interesting to know how your users are using your application.  Being able to track every single action made by a user is priceless when thinking about the direction of your app including what features to add, improve, or scrap.

Imaging spending all of your time on some complex feature to find out that only 1% of your users even care about that feature.  How could you know that only 1% of your users actually care about that feature unless you are doing some sort of tracking.

So before you add that super duper all in one end all be all 1337 feature to your app, consider reading the rest of this tutorial and add stat tracking first.  It is quick and painless and I promise that it will be totally worth it.

Configuring your Google Analytics Account

Google Analytics is a free server provided by Google.  If you dont already have an account, you can sign up for one with your existing Gmail account.  . Sign up and log in.

The first thing you will want to do is Add a new Website Profile.

On the next page:

  • Select Add a Profile for a new domain
  • Enter in some URL – This doesn’t really matter since google doesn’t use it to identify your app.  A good convention is iphone.yoursite.com or appname.yoursite.com so that you know these stats are for your iPhone app.
  • Select your country and timezone
  • Click Finish

Pretty simple… On the next screen, make sure you copy the Web Property ID. This number (begins with UA) is what we will be using to uniquely identify your application.

That’s all for the web side of things!  Now on to the iPhone part.

Download the Google Analytics Library and Add It To Your Application

This could not be easier.  Head on Over to . They explain much of the steps  so you could read the rest there, but I will lay them out in detail here with screesnhots.  Download the  and extract it.

There are 2 files that are important.  Drag both files from the Library folder into your XCode project.  These files are GANTracker.h and libGoogleAnalytics.a.

When XCode pops up the confirmation box, make sure that you check the box that says “Copy items into destination group’s folder (if needed)”.  This will ensure that the code gets place in your project directory.

Include CFNetwork and Link Against the sqlite framework

The google analytics framework requires the use of CFNetwork (for interent connection detection) and the sqlite framework (most likely to store events when the user does not have internet).

Let’s start by adding CFNetwork to the project. Right click on the frameworks folder and select Add -> Existing Frameworks.  Next, select CFNetwork.framework from the list and click Add.

Now we need to link the project against libsqlite3.0.dylib.  To do this Click Project -> Edit Active Target “<project name>” where <project name> is the name of your XCode project.

Next, click the + button at the bottom to bring up the library picker. Select libsqlite3.0.dylib and click Add

Including and Initializing the Tracker

Since the Analytics tracker is a singleton class, we only have to initialize it once and the rest of the application can use the same instance.

Let’s start by opening up the app delegate and adding the code to import the Google Analytics framework.

#import "GANTracker.h"

Now you need to initialize the tracker… Make sure you have the UA number handy that you received from Google earlier.  Add the following code to you applicationDidFinishLaunching method.

[[GANTracker sharedTracker] startTrackerWithAccountID:@"UA-15609865-3"
                                dispatchPeriod:10
                                delegate:nil];

Make sure you replace my UA number with yours. The dispatchPeriod variable tells the tracker how often to report back to Google. Google suggests using 10 seconds in their example so we’ll stick to that.

Tracking Pageviews and Custom Events

Google gives you 2 different ways to track how your users use the application.  The first way is via pageviews.  Pageviews work just like they do in the browser as if the user navigated to a new page in your website.  Some examples of when to use pageview are when you have a tab interface or a flipside view controller.  I would not suggest using a pageview every time the user performs an action such as click a button.

The second way is via custom events.  These are really cool.  With custom events, you can easily see HOW your users are using your application.  Examples of events are button clicks, typing in a textbox, submitting high scores, etc…

We will see an example of implementing each of these methods and take a look at how they appear inside of the Google Analytics website.

Pageview method

Here is an example of a pageview when the user first launches the app.  Put this code inside of your applicationDidFinishLaunching method.

NSError *error;
if (![[GANTracker sharedTracker] trackPageview:@"/app_launched"
                                        withError:&amp;error]) {
     // Handle error here
   }

Note that the “app_launched” is essentially our page name similar to index.html or aboutus.php. You can add this code anywhere in you app that you want to add a page view. Make sure you include the GANTrack.h file and change the pagename for each new location.

Event method
Here is an example of an event that gets fired when the user presses a Save button.

- (IBAction) saveTheWorld:(id) sender
{
        NSError *error;
        if (![[GANTracker sharedTracker] trackEvent:@"button_click"
                                             action:@"save_the_world"
                                              label:@"my_label"
                                              value:-1
                                          withError:&amp;error]) {
                // Handle error here
        }
}

What’s really cool about event tracking is you have 3 levels of customization. You have the category, the action, and the label. How you organize it is up to you, but make sure the grouping makes sense. In the example above, I will use the category “button_click” every time a user clicks any button. The action will determine which button was clicked (in this case, it’s “save_the_world”). Finally, the label is just another level. I’d suggest using the UDID of the users device.

Now that we have implemented our code, let’s take a look inside of our Google Analytics account and see what the stats look like.

This is just some of our sample data from another app.  Notice the interface is exactly the same as it is when you are tracking website statistics.  It shows you unique visits as well as pageviews.  You get all of the advanced reporting too including time spent on each “page”.

Now we take a look at events.  To find the actions click Content -> Event Tracking inside of your Google Analytics Page.

In the above screenshot, we see tracking for an event called “clap”.  It shows us the number of times the users “clapped” within a given day.

Conclusion

One last thing I want to mention before concluding this tutorial. Google Analytics stats are 1 day behind.  What this means is, you won’t see your stats appear immediately.  So, before you comment here because you don’t see the stats appearing, please please please wait one day and check your stats again.  That is all :)

Be one of the cool kids, .

Happy iCoding

  • Spacetrader

    How this code will send the information to Google Analytics? Is it via 3G/Wi-fi network?
    So after putting this code on my app the user will be alerted about the use of netwok?
    Is it necessary to specify on software description that the software is being monitoring through Google Analytics?

  • Tomislav

    I hope that you are aware that in the new developer agreement for iPhone OS 4.0 it is forbidden to send analytics data from your app.

  • http://www.localytics.com Brian

    Actually, Apple’s new developer agreement says that “device data” can’t be sent to a third party, unless approved by Apple. How that approval will be granted remains to be seen, but I suspect apps using analytic services that sell the data or use it for advertising will have a more difficult time getting approved.

    In any case, as the developer, you can still use a licensed product to collect data yourself. At Localytics, we offer both a third-party and first-party option for precisely that reason.

  • Ronny

    Hmm, can’t seem to find CFNetwork.framework. I’ve installed the SDK 4.0b2.

  • Ronny

    Never mind… I found it. Apparently I had chosen Mac OS frameworks.. *stupid me*

  • http://www.pierrephi.net Pierre-Phi

    Actually google analytics IS realtime but by default does not display current day.
    By clicking on the date range you can change the selection to include today and you will see up to the minute statistics

    Good tutorial!

  • http://returnvoid.co.uk Luke Price

    Your not the only one, I did exactly the same, in my defence it was late and I had run out of coffee.

  • RockHound

    I just tried this and it works! Be careful though cause Google keeps defaulting you back to yesterday’s numbers. You may have to reset it to today’s stats wile you are working in there.

  • http://iwyre.net/?p=3241 iWyre

    [...] How To Integrate Google Analytics Tracking Into Your Apps In 7 Minutes [...]

  • http://www.alexcurylo.com/blog/2010/04/29/google-analytics/ Google Analytics at Under The Bridge

    [...] How To Integrate Google Analytics Tracking Into Your Apps In 7 Minutes [...]

  • http://www.karamell.net/christians-dagbok-2010-05-02/ Christians dagbok – 2010-05-02 | En sur karamell

    [...] Shared How To Integrate Google Analytics Tracking Into Your Apps In 7 Minutes | iCodeBlog. [...]

  • http://iphone.zepho.com Bala Paranj

    How to track referrer URL? I want to know what keyword or search term resulted in the sales to calculate conversion ratio. This is more important than helping some numskull developer who adds unnecessary features.

  • http://brandontreb.com brandontreb

    @Bala

    This can’t be done. In order for this to happen, it would require that iTunes passed the referrer to your app. Would be a killer feature though.

  • http://www.google.com agustam

    pleas send my code

  • http://twf086.dubai.flipdevnet.com/en/blog/2010/05/12/how-to-integrate-google-analytics-into-your-app/ How to integrate Google Analytics into your app « AppsArabia

    [...] Click here to read the full details. [...]

  • jordan

    OK, this is pretty awesome. One of the reasons this is my favorite site.

  • Chris

    Great tutorial… it definitely makes sense to do this if it’s allowed, but do you know if this is affected by the new developer agreement, specifically 3.3.9? It’s been interpreted as mainly being about 3rd party ad servers that are owned by competitors (i.e. Google/Admob) but it seems like Google Analytics would run afoul of it as well, because it’s Google and your app is sending information to them as a third party.

  • ihtesham

    please help?

    in the track event code

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

    does the @”button_click” is method name and @”save_the_world” is UIButton and how to track google analytics because it’s not showing any results and i have created the account today.

    please help

  • ihtesham

    can somebody send me a sample code please

  • tuanka

    Hi Brandon! Great tutorial about iPhone. Can i translate it to my language and post it to my blog with link back?

  • http://www.ios4jailbreak.com/2010/07/how-to-integrate-google-analytics-tracking-into-your-apps-in-7-minutes/ iOS4 Jailbreak » How To Integrate Google Analytics Tracking Into Your Apps In 7 Minutes

    [...] the original: How To Integrate Google Analytics Tracking Into Your Apps In 7 Minutes [...]

  • Bimbam

    Did someone have problems with iOS4? I mean I try your tuto but it’s impossible to compile my project on simulator. Did you do any change to make it compatible?

  • http://tokoplusplus.com/how-to-put-google-analytic-to-your-iphone/ How to put Google analytic to your iPhone | GADGET TUTORIAL

    [...] same reasons you would integrate it into your site.  Google has extended their killer analytics platform to include mobile devices including the iPhone and Android [...]

  • specialk

    Cool? Cool doesn’t even come close to this – BIG kudo’s

  • Wbo99

    Ok this may be a dumb question, but am I supposed to put the code snippet in the IBAction inside of every IBAction/method I want to track? I think that particular part could use a little more detail…

    Thanks for the great tutorial!!

  • Lynn Gobin

    Thanks for a great tutorial. Worked like a charm!

  • Rita

    a very good tutorial, thank you so much! But how’d you track Dynamic value?

    I tried that in my didSelectRow to track which row user click, assigning a dictionary value to it and it doesn’t work.

    Would be great if someone could answer