ios NSURLConnection GET 请求返回-1005,“网络连接丢失”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25797339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:23:14  来源:igfitidea点击:

NSURLConnection GET request returns -1005, "the network connection was lost"

ioscocoa-touch

提问by Vikesh

I am trying to make a simple GET request using NSURLConnectionin XCode 6 (Beta7 2) on iOS 8 SDK, which is failing with "Code 1005, the network connection was lost". The call fails when I try to fetch http://www.google.comor a few other sample pages from the web, but succeeds if I make a request to a simple HTTP server on localhost (python -m SimpleHTTPServer). I have also tried using AFNetworkinglibrary (2.4.1) - URLs that fail with NSURLConnection also fail with the library.

我正在尝试NSURLConnection在 iOS 8 SDK 上的 XCode 6 (Beta7 2) 中使用一个简单的 GET 请求,该请求因“代码 1005,网络连接丢失”而失败。当我尝试从 Web获取http://www.google.com或其他一些示例页面时,调用失败,但如果我向 localhost ( python -m SimpleHTTPServer)上的简单 HTTP 服务器发出请求,则调用会成功。我也尝试过使用AFNetworking库 (2.4.1) - 因 NSURLConnection 失败的 URL 也因库失败。

Here's my code -

这是我的代码 -

NSString * url = @"http://0.0.0.0:8000";
// NSString * url = @"http://www.google.com";

NSLog(@"URL : %@", url);

// Mutable is probably not required, but just in case it REALLY WANTS me to set HTTP method
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[theRequest setHTTPMethod:@"GET"];

NSURLResponse *urlResponse = nil;
NSError *error = nil;

NSData * data = [NSURLConnection sendSynchronousRequest:theRequest
                                      returningResponse:&urlResponse
                                error:&error];

if (error == nil) {
    NSString *response = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSLog(response);
} else {
    NSString *response = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSLog(@"%@", [error userInfo]);
}

Logs:

日志:

2014-09-11 17:34:23.950 SearchExample[5092:2074687] URL : http://www.google.com
2014-09-11 17:34:24.023 SearchExample[5092:2074687] {
    NSErrorFailingURLKey = "http://www.google.com";
    NSErrorFailingURLStringKey = "http://www.google.com";
    NSLocalizedDescription = "The network connection was lost.";
    NSUnderlyingError = "Error Domain=kCFErrorDomainCFNetwork Code=-1005 \"The network connection was lost.\" UserInfo=0x7fc8515640a0 {NSErrorFailingURLStringKey=http://www.google.com/, NSErrorFailingURLKey=http://www.google.com/, _kCFStreamErrorCodeKey=57, _kCFStreamErrorDomainKey=1, NSLocalizedDescription=The network connection was lost.}";
    "_kCFStreamErrorCodeKey" = 57;
    "_kCFStreamErrorDomainKey" = 1;
}
2014-09-11 17:34:24.023 SearchExample[5092:2074687] URLResponse: (null)

回答by Ben-G

I have seen internet connectivity failing on the iPhone 6 simulator recently, resulting in the same errors. My Mac had a working internet connection the simulator did not. Restarting the simulator fixed the issue.

我最近在 iPhone 6 模拟器上看到互联网连接失败,导致相同的错误。我的 Mac 有一个有效的互联网连接,而模拟器没有。重新启动模拟器解决了这个问题。

回答by CMash

I was getting this error consistently on iOS 9 with certain network calls. Two were working fine but another two were not.

我在使用某些网络调用的 iOS 9 上始终收到此错误。两个工作正常,但另外两个没有。

It turned out to be caused by some incorrect parameters I was passing with the request's body... I wouldn't have expected that to cause a -1005 error... but it did.. Getting rid of the unnecessary parameters made it all work!

原来是由我与请求正文一起传递的一些不正确的参数引起的......我没想到会导致 -1005 错误......但它确实......摆脱了不必要的参数使一切成为可能工作!

回答by pcJmac

I've tried everything suggested on at least 15 answers from Google but not one of them solved my problem until I tried the following which totally addressed my issue. It appears that Wi-Fi connections can become corrupt on the Mac so if you remove the specific connection you are using and then connect again (by choosing the network and entering your password again) then this will fix the issue and no more dreaded -1005 “the network connection was lost” errors.

我已经尝试了谷歌至少 15 个答案中建议的所有内容,但没有一个解决了我的问题,直到我尝试了以下完全解决我的问题的方法。看起来,Mac 上的 Wi-Fi 连接可能会损坏,因此如果您删除正在使用的特定连接,然后再次连接(通过选择网络并再次输入密码),那么这将解决问题,不再害怕 -1005 “网络连接丢失”错误。

  • Go to the Wi-Fi symbol on your Mac's menubar and "Turn Wi-Fi Off"
  • Then choose "Open Network Preferences" (from the same menu, at the bottom).
  • In the bottom right-hand corner of the Network panel, choose "Advanced".
  • Select the network connection you were previously connected to.
  • Hit the minus symbol right below this table to delete this connection.
  • Hit "OK" for this window.
  • Hit "Apply" on the Network window.
  • Go back to the Wi-Fi symbol on your menubar and turn Wi-Fi back on.
  • Wait for your network connection to appear and then select it (and it will now ask for a password again because you deleted the connection info).
  • It will now remember this newly refreshed connection which should solve the problem!
  • 转到 Mac 菜单栏上的 Wi-Fi 符号并“关闭 Wi-Fi”
  • 然后选择“打开网络首选项”(从底部的同一菜单中)。
  • 在网络面板的右下角,选择“高级”。
  • 选择您之前连接的网络连接。
  • 点击此表正下方的减号以删除此连接。
  • 在此窗口中点击“确定”。
  • 在网络窗口中点击“应用”。
  • 返回菜单栏上的 Wi-Fi 符号并重新打开 Wi-Fi。
  • 等待您的网络连接出现,然后选择它(现在它会再次要求输入密码,因为您删除了连接信息)。
  • 它现在会记住这个新刷新的连接,它应该可以解决问题!

回答by MuraliMohan

Try to change request serialization in AFNetworking http or json. in my case that was json then i set to http. Now that is working.

尝试更改 AFNetworking http 或 json 中的请求序列化。就我而言,那是 json 然后我设置为 http。现在这正在起作用。

[[VTNetworkingHelper sharedInstance] performRequestWithPath:@"Your url  " withAuth:YES forMethod:@"POST" withRequestJSONSerialized:NO withParams:params withCompletionHandler:^(VTNetworkResponse *response) {
            if (response.isSuccessful) {
    }else {
    }];

回答by Rahul Serodia

I had Similar issue and restarting simulator didn't work. In my case I was able to hit web service alternatively like in odd time it would be successful and in even time it threw me with this error. I know its weird but it was the case somehow. Solved it with following approach in swift :

我有类似的问题,重新启动模拟器不起作用。在我的情况下,我能够像在奇数时间那样成功地访问 Web 服务,而在偶数时间它会出现此错误。我知道这很奇怪,但不知何故就是这样。在 swift 中使用以下方法解决了它:

 let urlconfig = NSURLSessionConfiguration.defaultSessionConfiguration()
                urlconfig.timeoutIntervalForRequest = 1
                urlconfig.timeoutIntervalForResource = 1
                let session = NSURLSession(configuration: urlconfig)

                let task = session.dataTaskWithRequest(request){(data,response,error) in
    //Processing
    }
 task.resume()

回答by Jayprakash Dubey

I have observed this issue occurs when you keep simulator active and your mac goes to sleep for long duration (say 5 to 10 hours). Then all of sudden you run app on simulator the it displays log as

我观察到当您保持模拟器处于活动状态并且您的 mac 长时间休眠(例如 5 到 10 小时)时会出现此问题。然后突然间你在模拟器上运行应用程序,它显示日志为

NSURLConnection GET request returns Code=-1005 "The network connection was lost."

The solution is to simply quit simulator, clean projectand re-run project.This worked for me!

解决方案是简单地退出模拟器清理项目重新运行项目。这对我有用!

回答by Mehul

Simple & sample solution, tested many times, working perfect.

简单的示例解决方案,经过多次测试,完美运行。

//Check response error using status code, and if you get -1005 then call that api again.

//使用状态码检查响应错误,如果得到-1005,则再次调用该api。

                if let strErrorReasonCode : Int = response.response?.statusCode {
                           if authentication_Errors_Range.contains(Alamofire_Error) {
                                self.POST(urlString, paramaters: paramaters, showLoader: showLoader, success: { (responseObject) in
                                    if response.result.isSuccess {
                                        if let value = response.result.value {
                                            let dictResponce = self.isValidated(value as AnyObject)
                                            if dictResponce.0 == true {
                                                success(dictResponce.1)
                                            }
                                            else {
                                                failure(dictResponce.1)
                                            }
                                        }
                                    }
                                }, failure: {_ in
                                    failure(jsonResponce)
                                })
                            }
                 }