Google Analytics API with Objective c, Part one

by roberto.vega 6. October 2009 13:37

Now that Google Analytics API is out and lot of people want to get access to the analytics data.
It is not to hard to retrieve the data. First thing that u need to do is access the Client Login and retrieve authentication token.
The easiest way to do this is:

NSString *post = [NSString stringWithFormat:@"accountType=GOOGLE&Email=%@&Passwd=%@&service=analytics&source=%@", email, password, source];

NSURL *url = [NSURL URLWithString:@"https://www.google.com/accounts/ClientLogin"];

NSMutableURLRequest *authRequest = [[NSMutableURLRequest alloc] initWithURL:url];
[authRequest setHTTPMethod:@"POST"];
[authRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[authRequest setHTTPBody:[post dataUsingEncoding:NSASCIIStringEncoding]];

NSHTTPURLResponse *authResponse;
NSError *authError;

NSData *receivedData = [NSURLConnection sendSynchronousRequest:authRequest returningResponse:&authResponse error:&authError];

NSString *authResponseData = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];

NSArray *lines = [authResponseData componentsSeparatedByString:@"\n"];
NSMutableDictionary *token = [NSMutableDictionary dictionary];

for(NSString *s in lines)
{ 
   NSArray *kvpair = [s componentsSeparatedByString:@"="];
   if([kvpair count]>1)
      [token setObject:[kvpair objectAtIndex:1] forKey:[kvpair objectAtIndex:0]];
}

[authRequest release];
[authResponseData release];

return [token objectForKey:@"Auth"];

Well that's the first part. Part two is how to retrieve analytics data from Google Analytics API.

Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.


Welcome to the Dropit blog!

Here we, the people that work at Dropit, will write about stuff that interests us. For example web development, especially with .NET and EPiServer - but we'll also talk about other techniques that interest us, marketing on the web, social phenomenons, pop culture, games and software development in general.