【问题标题】:NSURLConnection sendAsynchronousRequest:queue:completionHandler: doesn't call delegate method - didReceiveAuthenticationChallengeNSURLConnection sendAsynchronousRequest:queue:completionHandler: 不调用委托方法 - didReceiveAuthenticationChallenge
【发布时间】:2012-04-29 18:12:27
【问题描述】:

我有一个受摘要保护的 REST API。我想下载我的 JSON 响应,但首先我必须针对其余 api 进行身份验证。 我正在使用 sendAsynchronousRequest:queue:completionHandler: 处理我的请求。但我不知道如何处理摘要身份验证。我认为使用 NSURLConnectionDelegate 的委托方法 didReceiveAuthenticationChallenge 这应该是可能的?我在 .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"); }

【问题讨论】:

    标签: xcode rest delegates nsurlconnection digest


    【解决方案1】:

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

    NSURL *url = [NSURL URLWithString:@"http://restapi/"];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self]
    

    您需要实现更多委托方法才能接收响应。

    请注意,connection:didReceiveAuthenticationChallenge: 已被弃用,取而代之的是其他委托方法(请参阅此page)。

    【讨论】:

    • 谢谢,它现在正在工作,我正在使用新方法 connection:willSendRequestForAuthenticationChallenge: (所以我不必实现其他方法)。这意味着我不能使用方法 sendAsynchronousRequest?
    • 我猜sendAsynchronousRequest 适用于不需要不同回调的简单用例。您的案例更复杂,因为它涉及身份验证。所以你不能使用它。
    • 我找到了另一种使用 MKNetworkKit 提出请求的方法,它非常好用且易于使用。
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多