Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nishabe/bafc51fc9cd8e9f2fd5a to your computer and use it in GitHub Desktop.
Save nishabe/bafc51fc9cd8e9f2fd5a to your computer and use it in GitHub Desktop.
OBJC:Calling Web service using NSURLRequest & Blocks
- (IBAction)fetchGreeting;
{
NSURL *url = [NSURL URLWithString:@"http://rest-service.guides.spring.io/greeting"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
self.greetingId.text = [[greeting objectForKey:@"id"] stringValue];
self.greetingContent.text = [greeting objectForKey:@"content"];
}
}];
}
// More: https://spring.io/guides/gs/consuming-rest-ios/.
// But using sendAsynchronousRequest:queue:completionHandler has been deprecated from iOS9. Use [NSURLSession dataTaskWithRequest:completionHandler:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment