how to use sendAsynchronousRequest:queue:completionHandler: how to use sendAsynchronousRequest:queue:completionHandler: ios ios

how to use sendAsynchronousRequest:queue:completionHandler:


PArt 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 ([data length] > 0 && error == nil)        [delegate receivedData:data];    else if ([data length] == 0 && error == nil)        [delegate emptyReply];    else if (error != nil && error.code == ERROR_CODE_TIMEOUT)        [delegate timedOut];    else if (error != nil)        [delegate downloadError:error];}];


Here is a sample:

NSString *urlAsString = @"http://www.cnn.com";NSURL *url = [NSURL URLWithString:urlAsString];NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];[NSURLConnection         sendAsynchronousRequest:urlRequest         queue:[[NSOperationQueue alloc] init]         completionHandler:^(NSURLResponse *response,                             NSData *data,                             NSError *error)         {         if ([data length] >0 && error == nil)         {                        // DO YOUR WORK HERE         }         else if ([data length] == 0 && error == nil)         {             NSLog(@"Nothing was downloaded.");         }         else if (error != nil){             NSLog(@"Error = %@", error);         }     }];


For the queue param, try this magic:

[NSOperationQueue mainQueue]

This works great if you are updating the UI on completion of the request since main queue is the main thread. It essentially gives you the previous behavior of NSURLConnection. If however you plan on writing to file or decompressing then you can complete on a background queue and then dispatch async back to the main queue for the UI updates.