NSURLConnection sendAsynchronousRequest:queue:completionHandler:不调用委托方法 - didReceiveAuthenticationChallenge
问题描述:
我有一个由摘要保护的REST API。我想下载我的JSON响应,但首先我需要对其余的api进行身份验证。 我正在做我的请求与sendAsynchronousRequest:queue:completionHandler :.但我不知道如何处理摘要认证。我认为用NSURLConnectionDelegate的委托方法didReceiveAuthenticationChallenge应该有可能吗?我在.h文件中声明了NSURLConnectionDelegate,并在实现中添加了该方法。但没有任何反应。任何建议如何处理与“sendAsynchronousRequest:queue:completionHandler:”?NSURLConnection sendAsynchronousRequest:queue:completionHandler:不调用委托方法 - didReceiveAuthenticationChallenge
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"); }
答
如果您指定实例作为连接代表的connection:didReceiveAuthenticationChallenge:
才会被调用。要做到这一点,你需要使用不同的方法来启动的要求,例如:
NSURL *url = [NSURL URLWithString:@"http://restapi/"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self]
你需要实现以接收响应进一步的委托方法。
注意connection:didReceiveAuthenticationChallenge:
是赞成的其他委托方法已过时(请参阅本page)。
感谢,它的工作,现在和我使用新的方法连接:willSendRequestForAuthenticationChallenge:(所以我不必须实施其他方法)。这意味着我不能使用方法sendAsynchronousRequest? – milepile 2012-04-18 16:38:24
我猜'sendAsynchronousRequest'适用于不需要不同回调的简单用例。你的情况更复杂,因为它涉及认证。所以你不能使用它。 – Codo 2012-04-18 17:05:09
我找到了另一种方法来使用MKNetworkKit来完成我的请求,这非常简单易用。 – milepile 2012-04-24 10:49:30