Take the 2-minute tour ×

In my app i'm creating now i use goo.gl's url shortener api to shorted urls. I have it nearly working, I can send the longUrl to retrieve the short one in a NSString but it's in this format:

"kind": "urlshortener#url",
"id": "http://goo.gl/something",
"longUrl": "http://somethinglonggggg/"

I just wondered if there is a way to just take the id (short url) from that.

Here's what I have so far:

NSString *longURL = urlText.text;
NSData *reqData = [[NSString stringWithFormat:@"{\"longUrl\":\"%@\"}", longURL] dataUsingEncoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [NSMutableURLRequest
                                requestWithURL:[NSURL URLWithString:@"https://www.googleapis.com/urlshortener/v1/url"]
[request setHTTPMethod:@"POST"];
[request setHTTPBody:reqData];

NSError *err = [[NSError alloc] init];
NSData *retData = [NSURLConnection sendSynchronousRequest:request

if([err domain]) return;

NSString *retString = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];

if([retString rangeOfString:@"\"error\""].length) return;

NSLog(@" longUrl equals %@ ", longURL);
NSLog(@" retString equals %@ ", retString);

urlText.text = retString;
share|improve this question
Are you sure the returned value is really a string, and not a dictionary? It seems it is a dictionary. –  EmptyStack Sep 3 '11 at 4:50
Hmm, i'm not sure to be honest, when I did <NSLog(@" retString equals %@ ", retString); it worked fine. If it was a dictionary how would i be able to get the url from it? –  Christopher Hannah Sep 3 '11 at 4:53
actually it's definitely a string, i tried to set it to a dictionary and wouldn't work. –  Christopher Hannah Sep 3 '11 at 4:57
It looks like JSON return - It might be easier to use one of the JSON parsing libraries. –  Abizern Sep 3 '11 at 4:59
Would you be able to help with JSON? :) –  Christopher Hannah Sep 3 '11 at 5:01
show 1 more comment

1 Answer

You defenitively need to turn that into an NSDictionary (that JSON syntax is for a dictionary, or an object, however you want to call it.

The google API for Objective-C supports JSON parsing to turn the response into objects.

You can find it here.

If all you need is parsing the JSON, I would recommend either JSONkit or TouchJSON.

They both work in very similar ways, you give them the string and they will give you back objects.

The info for the individual usage of the libraries can be found on the readme of the respective project, there you will find how easy to use they are.

You would then acces the different values using:

NSString *short URL = [object valueForKey:@"id"];

This is the best way to interact with REST services.

Hope it helps!

share|improve this answer
That worked perfectly :) –  Christopher Hannah Sep 7 '11 at 17:10
Im glad it helped, please accept the answer if it solved your problem and tell me if you need any more help! –  Zebs Sep 7 '11 at 18:35
add comment

Your Answer


