Xcode and iOS: Connecting the Google API library and Executing a Google Analytics Request

Xcode and iOS: How to easily connect the Google API library

Preparing Xcode

Open up Xcode and start a new iOS “Single View Application”.
Specify the

     Product name: GoogleAnalyticsTest
     Organizetion Name: TestingLabs
     Organization Identifier: com.story
     Language: Objective-C
     Devices: iPhone
     **Check** Use Core Data

Configure the new Project
Right click on the project name (GoogleAnalyticsTest) and select New Group.
Creating a new Group

Name the group “GoogleAPI”

Downloading the Google API

Open up the terminal, navigate to any folder, and download the Google API by executing

svn checkout http://google-api-objectivec-client.googlecode.com/svn/trunk/ google-api

Connecting the Google API

Now we are ready to connect the two

  1. Open the folder containing the Google API from the previous step.
  2. Navigate to the google-api/Source folder.
  3. Drag all the folders into the GoogleAPI group within Xcode.
    1. Connecting the Google API
  4. Select Copy Items if needed, Create groups, and add to targets GoogleAnalyticsTest.
    1. Select Copy items
  5. It’ll index and process the files for a couple of seconds …..
  6. Now select GoogleAnalyticsTest and click on “Build Phases”.
  7. Expand “Compile Sources” select all the items and remove them.
    1. Easiest way is by clicking the top one, scrolling to the very bottom and while holding shift clicking on the last item. This will select them all and just click the minus sign or pressing delete will remove them all.
  8. Now we drag over the 3 main files from the GoogleAPI into “Compile Sources”.
    1. GTLCommon_sources.m
    2. GTLDefines.h
    3. GTLNetworking_sources.m
  9. Now select all 3 files from Compile Sources and double click on Compiler Flags and insert -fno-objc-arc
    1. 3 Items for -fno-objc-arc
  10. We also need to drag the original files
    1. AppDelegate.h AppDelegate.m
    2. ViewController.h ViewController.m
    3. main.m from “Supporting Files”
  11. From the Services -> Analytics ->Generated folder we drag over
    1. GTLAnalytics.h
    2. GTLAnalytics_Sources.m
  12. We also need to import the Security.framework and SystemConfiguration.framework in Link Binary with Libraries
  13. Fully configured

Now the app should succesfully compile and run with the blank screen, since nothing else has been setup yet.

OAuth2 Authentication using Google API for Objective C

Now with the libraries connected we can start building the app.
Create a Login button on the main story board.
Open up Assistant View and Drag the control drag to make an Action called loginButtonClick

Within ViewController.m import the necessary headers

#import "GTLDefines.h"
#import "GTLAnalytics.h"
#import "GTLServiceAnalytics.h" 
#import "GTMOAuth2ViewControllerTouch.h"

Specify the constants and objects we’ll need

static NSString *const kKeychainItemName = @"GoogleAnalytics:Test";
static NSString *const kClientId = @"MYCLIENTID";
static NSString *const kClientSecret = @"MYCLIENTSECRET";
static NSString *kGTLAuthScopeAnalyticsEdit1 = @"https://www.googleapis.com/auth/analytics https://www.googleapis.com/auth/analytics.edit";
GTMOAuth2Authentication *ga_auth;
GTLServiceAnalytics *service;
BOOL isAuthorized;

The loginButtonClick function:

- (IBAction)loginButtonClick:(id)sender {
if(!isAuthorized) {
    // Sign in.
SEL finishedSelector = @selector(viewController:finishedWithAuth:error:);

GTMOAuth2ViewControllerTouch *authViewController =
    [[GTMOAuth2ViewControllerTouch alloc] 

[self presentModalViewController:authViewController
} else {
    [GTMOAuth2ViewControllerTouch removeAuthFromKeychainForName:kKeychainItemName];
    isAuthorized = NO;

We also specify these two functions:

- (void)isAuthorizedWithAuthentication:(GTMOAuth2Authentication *)auth {
NSLog(@"User Logged In %@", auth);
isAuthorized = YES;
service = [[GTLServiceAnalytics alloc] init];
[service setAuthorizer:auth];
    // [self performSegueWithIdentifier:@"LoggedIn" sender:self];

- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
  finishedWithAuth:(GTMOAuth2Authentication *)auth
             error:(NSError *)error {
[self dismissModalViewControllerAnimated:YES];
if (error == nil) {
    NSLog(@"NO ERROR: %@",error);
    [self isAuthorizedWithAuthentication:auth];
    ga_auth = auth;
    NSLog(@"Authenticated with no Error %@ \n", error);

Now when we run the app we’ll have a functioning Login button that directs us to the Google authentication screen.

Using the Keychain to store Authentication information

Since above we already store the Access and refresh tokens within the keychain all we need to do every time the app opens is to check it and create a new authentication object. Inside our viewDidLoad we just add…

ga_auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
if ([ga_auth canAuthorize]) {
    [self isAuthorizedWithAuthentication:ga_auth];

Executing a Google Analytics Properties Request

GTLQueryAnalytics *query = [GTLQueryAnalytics queryForManagementAccountSummariesList];

[service executeQuery:query completionHandler:^(GTLServiceTicket *ticket,                                                        GTLAnalyticsAccountSummaries *properties,
    NSError *error) {
    if (error == nil) {
        NSLog(@"files: %@",properties);
        int i =0;
        for(;i < properties.items.count;i++ ){
            NSLog(@"%d : %@ " , i, [properties.items objectAtIndex:i]);

    } else {
        NSLog(@"An error occurred: %@", error);

Now the function just needs to be executed and we’ll do that from the
isAuthorizedWithAuthentication method so at the very bottom just add the [self loadData];

- (void)isAuthorizedWithAuthentication:(GTMOAuth2Authentication *)auth {
NSLog(@"User Logged In %@", auth);
isAuthorized = YES;
service = [[GTLServiceAnalytics alloc] init];
[service setAuthorizer:auth];
[self loadData];
// [self performSegueWithIdentifier:@"LoggedIn" sender:self];   

Now the app prints out all the properties associated with a Google Analytics account.
GoogleAnalytics Properties Log

Download the full project here


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s