【问题标题】:Handling a 401 response with sendAsynchronousRequest:queue:completionHandler:使用 sendAsynchronousRequest:queue:completionHandler 处理 401 响应:
【发布时间】:2012-04-03 04:25:24
【问题描述】:

我正在使用新的 iOS 5 方法发出异步 url 请求:sendAsynchronousRequest:queue:completionHandler:。这使用块来处理响应,但没有调用 NSURLConnectionDelegate 委托方法?在这种情况下,我看不到为 NSUrlConnection 类设置委托的方法吗?

[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);              
   }
}];

我需要委托方法的原因是因为我的一个调用得到了 401 响应,iOS 以不同的方式处理该响应 - 将身份验证推迟到委托方法。当 401 响应返回时 - httpResponse.statusCode 只是“0”。

有没有办法阻止 iOS 尝试以不同的方式处理 401?特别是,我认为我需要使用 continueWithoutCredentialForAuthenticationChallenge: 委托方法 - 但在这种情况下没有调用委托。

谢谢!

【问题讨论】:

标签: ios cocoa-touch


【解决方案1】:

您需要使用 NSURLConnection 实例并为此使用委托。 sendAsynchronousRequest:queue:completionHandler: 是相同的快捷方式,但具有没有委托的默认行为。

【讨论】:

    【解决方案2】:
    NSMutableURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    
    NSURLConnection *connection = [[NSURLConnection alloc] nitWithRequest:request delegate:self];
    

    使用上述方法,这将触发委托方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      • 2020-11-07
      • 1970-01-01
      相关资源
      最近更新 更多