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"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:20];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:reqData];
NSError *err = [[NSError alloc] init];
NSData *retData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:&err];
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;
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:
This is the best way to interact with REST services.
Hope it helps!