This example takes a simple view controller, calls the googlemaps api, and parses the returning JSON results.
The network call
NSURLConnection is the object that handles the HTTP request. You basically define the URL you are connecting to, implement the required delegates, and then get notified when the request is complete in the connectionDidFinishLoading method.
Parsing the JSON
NSJSONSerialization seems to currently be the best way to take your URL response and convert it into an iOS JSON object.
With this object you can then parse the response, looking at the keys and values, and then manually determine which elements you want to extract.
The code
Putting all that together, you get something that looks like this:
ViewController.m
#import "spike1ViewController.h" @interface spike1ViewController() @property (nonatomic, strong) NSMutableData *responseData; @end @implementation spike1ViewController @synthesize responseData = _responseData; - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"viewdidload"); self.responseData = [NSMutableData data]; NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AIzaSyAbgGH36jnyow0MbJNP4g6INkMXqgKFfHk"]]; [[NSURLConnection alloc] initWithRequest:request delegate:self]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"didReceiveResponse"); [self.responseData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.responseData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"didFailWithError"); NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"connectionDidFinishLoading"); NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]); // convert to JSON NSError *myError = nil; NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError]; // show all values for(id key in res) { id value = [res objectForKey:key]; NSString *keyAsString = (NSString *)key; NSString *valueAsString = (NSString *)value; NSLog(@"key: %@", keyAsString); NSLog(@"value: %@", valueAsString); } // extract specific value... NSArray *results = [res objectForKey:@"results"]; for (NSDictionary *result in results) { NSString *icon = [result objectForKey:@"icon"]; NSLog(@"icon: %@", icon); } } - (void)viewDidUnload { [super viewDidUnload]; } @end
You can tell it’s working by looking at the output in the NSLogs. Should see something that looks like this:
Brian Kelly (@spilth)
Feb 01, 2012 @ 18:42:05
I’ve been bookmarking this series as posts. I’m working my way through “iOS SDK Development” by PragProg and these posts are a nice compliment to them material in the book.
JR
Feb 01, 2012 @ 20:05:48
Thanks Brian.
I have a copy of the iOS SDK book but haven’t had an opportunity to reach for it yet.
If you’ve been reading my other posts you’ll know I’ve been going through the stanford course notes with a fine tooth come. A lot of inspiration comes form there.
http://itunes.apple.com/itunes-u/ipad-iphone-application-development/id473757255
I just finished those, so now I am going to be spiking some stuff I still need to figure out.
But thanks for the comment. Nice to know someone is reading.
Cheers – Jonathan
Brian Kelly (@spilth)
Feb 01, 2012 @ 20:19:39
I put the iTunes U course on my list of To Do’s as well. I’m looking to do a simple Rest-based app for my site http://oktoride.com/ but still have a lot to learn. I only every played with the iPhone 3.0 SDK briefly previously.
I have “The Agile Samurai” which has been a good guide for an internal project I’ve been running using some agile practices. I’ve recommended it to a few friends who have found it helpful as well.
JR
Feb 01, 2012 @ 21:04:48
Hey I love the site! I am a winter bike commuter and something like your site would be perfect for some rides around here.
Good luck with the project and thanks for recommending the book.
xcode newbies
May 05, 2012 @ 07:18:10
Thanks for the comprehensive example. I can make a JSON call following line by line. (Although you have thankfully provided complete code, I wrote method by method and got to know how it works).
At one point I wrongly implemented delegating method from NSURLConnectionDownloadDelegate
@required
– (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *) destinationURL;
and I was stuck. But I double checked with your code and I figured out i should implement
– (void)connectionDidFinishLoading:(NSURLConnection *)connection
Again, Thanks.
JR
May 07, 2012 @ 13:09:44
Hey you are very welcome. Glad it helped. Good luck!
Aarti Arjunwadkar
Jul 05, 2012 @ 07:45:36
Thanks,
It was really helpful
praveen sharma
Aug 12, 2012 @ 10:38:25
it was really helpful
Jerry Walton
Aug 17, 2012 @ 14:18:35
by convention your class name should begin with uppercase
should be “Spike1ViewController”, not “spike1ViewController”
member variables should be lower case as in spike1ViewController
thanks for the article.
JR
Aug 27, 2012 @ 21:30:20
Indeed you are correct Jerry. Thanks for pointing out.
Elia
Nov 17, 2012 @ 15:04:05
Hi,
I have run your code (thank you) but it never enter in the method “didReceiveData”. Where I can try to search the issue?
Prasanth
Nov 21, 2012 @ 12:39:01
Thanks a lot…nice tutorial..
David Geghamyan
Dec 06, 2012 @ 12:01:12
Thank You!
Jorge
Jan 06, 2013 @ 18:39:05
Hi Brian!
I follow your article, but the accentuation coming fail…
The word “idéia” coming “id\U00e9ia”.
How can i fix it?
Thomas
Feb 11, 2013 @ 22:58:46
have you tried to set the params after the request definition ?
like this :
[request setHTTPBody:[[NSString stringWithFormat:@”param1=%@”,param1] dataUsingEncoding:NSASCIIStringEncoding]];
In this way, you can use NSASCIIStringEncoding
I hope it help you because I new user in iOS and I am a few lost.
(and I’m not english, as you can see)
Nelson
Jan 18, 2013 @ 08:58:49
I get a compiler warning @ line 17 so I had to add:
NSURLConnection* conn [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
Is that correct?
Max
Aug 21, 2013 @ 21:40:04
How can I do with 2 URL ???
Help please.
Adedayo Omosanya
Aug 15, 2014 @ 10:01:59
Thankyou for an excellent tutorial.
HOWEVER, I HAVE A PROBLEM.
I successfully get: didRecieveResponse, connectionDidFinishLoading and Recieved 2255 bytes of data. After that however, the program crashes – when trying to “show all values”. Why might this be? I am using my own url btw which outputs data in JSON format
JmB
Sep 25, 2014 @ 17:02:19
I have the same problem as Adedayo. I added some NSLogs. The responseData is null, so the program ends there, it does not crash.
JmB
Sep 25, 2014 @ 17:03:32
I had added another website though. If you are trying with the above URL info…that API does not exist anymore, was the error I received.
cadomagenge
Apr 27, 2015 @ 08:19:36
Awesome post. I loved the way you presented each steps. Thanks for share.
fennielee
May 19, 2015 @ 03:14:41
This is great, thanks!
Đăng Hưng Nguyễn
Aug 04, 2015 @ 11:01:36
please, source code for me