4

I have a REST API which is secured by digest. I want to download my JSON response, but first I've to authenticate against the rest api. I'm doing my Requests with sendAsynchronousRequest:queue:completionHandler:. But I don't know how to handle the digest authentication. I thought with the delegate method didReceiveAuthenticationChallenge of NSURLConnectionDelegate this should be possible? I've declared in the .h file the NSURLConnectionDelegate and added in the implementation the method. But nothing happens. Any advice how to handle this with "sendAsynchronousRequest:queue:completionHandler:" ?

NSURL *url = [NSURL URLWithString:@"http://restapi/"];

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)
         [self receivedData:data];
     else
         NSLog(@"error");
 }];

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSLog(@"did get auth challenge"); }
milepile
  • 141
  • 1
  • 3
  • 10

2 Answers2

3

The connection:didReceiveAuthenticationChallenge: will only be called if you specify your instance as the delegate of the connection. To do so you'll need to use a different method to start the request, e.g.:

NSURL *url = [NSURL URLWithString:@"http://restapi/"];

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self]

You will need to implement further delegate methods in order to receive the response.

Note that connection:didReceiveAuthenticationChallenge: is deprecated in favor of other delegate methods (see this page).

Codo
  • 75,595
  • 17
  • 168
  • 206
  • thanks, it's working right now and I'm using the new method connection:willSendRequestForAuthenticationChallenge: (so I don't have to implement the other methods). That means I can't use the Method sendAsynchronousRequest? – milepile Apr 18 '12 at 16:38
  • I guess `sendAsynchronousRequest` is for simple use cases where you don't need the different callbacks. Your case is more complex as it involves authentication. So you can't use it. – Codo Apr 18 '12 at 17:05
  • I have found another way to make my requests with the MKNetworkKit, which is great and simple to use. – milepile Apr 24 '12 at 10:49
0

Have a look at this question chain set might be this can help:

Authentication with NSURLConnection sendAsynchronousRequest with completion handler

Community
  • 1
  • 1