Friday, May 22, 2009

Google Client Login, analytics with Objective c, Part one

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 of how to retrieve analytics data from Google Analytics API

No comments:

cms and stuff - new iPhone :)