ios - NSUrlConnection -> NSUrlSession;不再为 completionHandler 错误返回 NSError

标签 ios nsurlconnection nsurlsession

我有一些长期存在的代码,它们使用 NSUrlConnection 发出异步请求,并使用 completionHandler block 来处理它。不久前,我切换到 NSUrlSession,用于一些小的附加功能,但主要假设它们在实现上是相似的。他们都以相同的方式获取了我的 completionHandler block ,并在完成时调用它。设置有点不同。

最近我发现了一个令人不安的问题,当实际发生错误时,NSUrlSession 没有将 NSError 返回到 completionHandler block 。用例是针对 http 401 身份验证问题,通常返回 NSError 代码 -1012。对于 NSUrlSession,NSError 为零。

无论我是否使用委托(delegate),这都是正确的。并且 didFailWithError 委托(delegate)也没有返回。

为什么 NSUrlSession 不会返回此错误?

void (^connectionCompletionHandlerBlock)(NSData *data, NSURLResponse *response, NSError *error) = ^(NSData *data, NSURLResponse *response, NSError *error){
   if(error){
      // handle error
      if(error.code == -1012){  // such as http 401 login error
         // auth error
      }
   } else {
      // no error
   }
}

NSString *url = @"http://blahblah.com";
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

// configure urlRequest with params, etc

NSUrlConnection方式:(nserror -1012返回401错误)
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:connectionCompletionHandlerBlock];

NSUrlSession 方式:(没有 nserror -1012 返回 401 错误)
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
NSURLSessionDataTask *task = [session dataTaskWithRequest:urlRequest completionHandler:connectionCompletionHandlerBlock];
[task resume];

我希望为我的 401 得到的 NSError:

错误域=NSURLErrorDomain 代码=-1012 "(null)"UserInfo={NSErrorFailingURLStringKey= https://api/blah , NSUnderlyingError=0x600004047890 {错误域=kCFErrorDomainCFNetwork 代码=-1012 "(null)"UserInfo={_kCFURLErrorAuthFailedResponseKey={url = https://api/blah }}}, NSErrorFailingURLKey= https://api/blah }

最佳答案

稍作研究后发现。 NSUrlSession 按照设计不返回服务器端错误。
来自 NSUrlSession Apple documentation

Note: NSURLSession does not report server errors through the error parameter. The only errors your app receives through the error parameter are client-side errors, such as being unable to resolve the hostname or connect to the host.

Server-side errors are reported through the HTTP status code in the NSHTTPURLResponse object. For more information, read the documentation for the NSHTTPURLResponse and NSURLResponse classes.

关于ios - NSUrlConnection -> NSUrlSession;不再为 completionHandler 错误返回 NSError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42638476/

相关文章:

ios - 设备锁定时 NSURLConnection 应用程序崩溃

swift - 如何等待 Swift 的 URLSession 完成后再运行?

ios - 不确定为什么 NSURLSession 超时

IOS Touch ID公钥和私钥

iphone - iPhone应用程序语言的问题即时更改

iphone - NSURLConnection - 在使用另一个类作为委托(delegate)时以及存在身份验证挑战时获取响应数据

swift - NSURLConnection 响应返回 500 状态码

ios - 适用于 iOS 的 Garmin Connect API

ios - 无法将类型 'nil' 的值分配给类型 'NSMutableArray' 的值

ios - 如何设置状态栏和导航栏之间的空间?