Let’s say I want to get tweets from Twitter.
- I send HTTP request to Twitter with “Accept” header set to “application/json”
- Receive returned JSON and parse it
- Do whatever I want with parsed JSON
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
//The URL of JSON service NSString *_urlString = @"http://twitter.com/status/user_timeline/andri_yadi?count=50"; NSURL *_url = [NSURL URLWithString:_urlString]; NSMutableURLRequest *_request = [NSMutableURLRequest requestWithURL:_url]; NSDictionary *_headers = [NSDictionary dictionaryWithObjectsAndKeys:@"application/json", @"accept", nil]; [_request setAllHTTPHeaderFields:_headers]; [NSURLConnection sendAsynchronousRequest:_request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse* response, NSData* data, NSError* error) { NSError *_errorJson = nil; NSArray *_tweetArr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&_errorJson]; if (_errorJson != nil) { NSLog(@"Error %@", [_errorJson localizedDescription]); } else { //Do something with returned array dispatch_async(dispatch_get_main_queue(), ^{ [self didLoadedTweetsWithResult:_tweetArr]; }); } }]; |
Above code uses two API provided only in iOS 5 or later:
- Asynchronous and block-based handler NSURLConnection
- NSJSONSerialization
You don’t need any third party libraries.