5

I'm making an async url request with the new iOS 5 method: sendAsynchronousRequest:queue:completionHandler:. This uses a block to handle the response, but no NSURLConnectionDelegate delegate methods are being called? I can't see a way to set the delegate for the NSUrlConnection class in this instance?

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

   NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

   NSLog(@"HTTP response code: %i", httpResponse.statusCode);

   if (error != nil) {
       NSLog(@"There was error with the synchronous request: %@", error.description);              
   }
}];

The reason I need the delegate methods is because one of my calls gets a 401 response, which iOS handles in a different way - deferring authentication to delegate methods. When a 401 response comes back - httpResponse.statusCode is just "0".

Is there a way to stop iOS from trying to handle a 401 differently? In particular, I'm thinking I need to use the continueWithoutCredentialForAuthenticationChallenge: delegate method - but no delegates are being called in this case.

Thanks!

paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
wows
  • 10,687
  • 7
  • 27
  • 27
  • Use one of the connection methods with a delegate, like initWithRequest:delegate: – Adam Shiemke Apr 03 '12 at 04:30
  • Have a look at this answer : http://stackoverflow.com/questions/12828060/authentication-with-nsurlconnection-sendasynchronousrequest-with-completion-hand – Ravi Dalmia Jul 29 '13 at 12:34

2 Answers2

1

You need to use a NSURLConnection instance and use a delegate for that. The sendAsynchronousRequest:queue:completionHandler: is a shortcut for the same but with the default behavior without a delegate.

Igor
  • 4,778
  • 2
  • 22
  • 12
0
NSMutableURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

NSURLConnection *connection = [[NSURLConnection alloc] nitWithRequest:request delegate:self];

use the above method this will fire the delegates methods.

Raj
  • 5,895
  • 4
  • 27
  • 48