xcode – NSURLConnection sendAsynchronousRequest:queue:completionHandler:不调用委托方法 – didReceiveAuthenticationChallenge

前端之家收集整理的这篇文章主要介绍了xcode – NSURLConnection sendAsynchronousRequest:queue:completionHandler:不调用委托方法 – didReceiveAuthenticationChallenge前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个REST API,它由摘要保护.我想下载我的 JSON响应,但首先我要对其余的api进行身份验证.
我正在使用sendAsynchronousRequest执行我的请求:queue:completionHandler:.但我不知道如何处理摘要身份验证.我想用委托方法didReceiveAuthenticationChallenge的NSURLConnectionDelegate这应该可行吗?我在.h文件中声明了NSURLConnectionDelegate,并在实现中添加了该方法.但没有任何反应.有关如何使用“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"); }

解决方法

连接:didReceiveAuthenticationChallenge:仅当您将实例指定为连接的委托时才会被调用.为此,您需要使用不同的方法来启动请求,例如:

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

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

您需要实现进一步的委托方法才能接收响应.

请注意,不建议使用connection:didReceiveAuthenticationChallenge:以支持其他委托方法(请参阅此page).

猜你在找的Xcode相关文章