Asynchronous request example

Xcode picture Xcode · May 17, 2013 · Viewed 21k times · Source
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http:///];
NSURLRequest *req = [[NSURLRequest alloc]initWithURL:url];
NSURLConnection *con = [[NSURLConnection alloc]initWithRequest:req delegate:self startImmediately:YES];

In my project I used sendSynchronousRequest on NSURLConnection. It gives me crash sometimes.

So I convert this code to AsynchronousRequest. I could not find suitable code.

Somebody give me link or post code which suitable to my code. Any hep will be appreciated.

Answer

Harish picture Harish · May 17, 2013

There are couple of things you could do.

  1. You can use sendAsynchronousRequest and handle the callback block.
  2. You can use AFNetworking library, which handles all your requests in asynchronous fashion. Very easy to use and set up.

Code for option 1:

NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
  if (error) {
    //NSLog(@"Error,%@", [error localizedDescription]);
  }
  else {
    //NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
  }
}];

Code for option 2:

You might want to download the library & include it in your project first. Then do the following. You can follow the post on setting up here

NSURL *url = [NSURL URLWithString:@"http://httpbin.org/ip"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"IP Address: %@", [JSON valueForKeyPath:@"origin"]);
} failure:nil];

[operation start];