使用sendAsynchronousRequest处理401响应:queue:completionHandler:

时间:2012-04-03 04:25:24

标签: ios cocoa-touch

我正在使用新的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:委托方法 - 但在这种情况下没有调用委托。

谢谢!

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

NSMutableURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

NSURLConnection *connection = [[NSURLConnection alloc] nitWithRequest:request delegate:self];

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