我有一个应用程序,可以在Xcode6-Beta1和Xcode6-Beta2与iOS7和iOS8上正常工作。但是对于Xcode6-Beta3, Beta4, Beta5,我在iOS8上面临网络问题,但在iOS7上一切都很好。我得到错误“网络连接丢失”。错误如下:

Error: ErrorDomain =NSURLErrorDomain Code=-1005 "The network connection was lost."UserInfo=0x7ba8e5b0 {NSErrorFailingURLStringKey=, _kCFStreamErrorCodeKey=57, NSErrorFailingURLKey=, NSLocalizedDescription=网络连接丢失。, _kCFStreamErrorDomainKey=1, NSUnderlyingError=0x7a6957e0 "The network connection was lost."}

我使用AFNetworking 2。X和下面的代码片段进行网络调用:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:policy];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

[manager POST:<example-url>
   parameters:<parameteres>
      success:^(AFHTTPRequestOperation *operation, id responseObject) {
          NSLog(@“Success: %@", responseObject);
      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          NSLog(@"Error: %@", error);
      }];

我尝试了NSURLSession,但仍然收到相同的错误。


当前回答

我也有同样的问题,问题是Alomofire和NSUrlSession的bug。当你从safari或电子邮件返回到应用程序时,你需要等待近2秒才能通过Alamofire进行网络响应

 DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
       Your network response
}

其他回答

如果有人在将文件上载到后端服务器时得到此错误,请确保接收服务器具有您的媒体允许的最大内容大小。在我的例子中,NGINX需要一个更高的client_max_body_size。NGINX会在上传完成之前拒绝请求,这样就不会返回错误代码。

如果问题发生在设备上,检查流量是否通过代理(设置> Wi-Fi > (info) > HTTP代理)。我已经设置好了与Charles一起使用的设备,但忘记了代理。似乎没有Charles实际运行,就会出现这个错误。

我通过VPN连接。去使能VPN解决了问题。

当传递一个NSURLRequest到一个NSURLSession而没有设置请求的HTTPMethod时,我击中了这个错误。

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlComponents.URL];

ErrorDomain =NSURLErrorDomain Code=-1005 "The network connection was lost."

不过,添加HTTPMethod,连接就可以正常工作了

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlComponents.URL];
[request setHTTPMethod:@"PUT"];

2017年1月25日,苹果发布了一份关于此错误的技术问答:

Apple Technical Q&A QA1941 Handling “The network connection was lost” Errors A: NSURLErrorNetworkConnectionLost is error -1005 in the NSURLErrorDomain error domain, and is displayed to users as “The network connection was lost”. This error means that the underlying TCP connection that’s carrying the HTTP request disconnected while the HTTP request was in progress (see below for more information about this). In some circumstances NSURLSession may retry such requests automatically (specifically, if the request is idempotent) but in other circumstances that’s not allowed by the HTTP standards. https://developer.apple.com/library/archive/qa/qa1941/_index.html#//apple_ref/doc/uid/DTS40017602