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

7

45

I am trying to make a simple GET request using NSURLConnection in 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.com or 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 AFNetworking library (2.4.1) - URLs that fail with NSURLConnection also fail with the library.

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)
Mauretania answered 11/9, 2014 at 21:35 Comment(4)
kCFStreamErrorDomainKey 1 is the POSIX domain, which means that kCFStreamErrorCodeKey 57 is "socket not connected". Is the firewall on your Mac not allowing Xcode/simulator to make external connections?Espouse
@Espouse The firewall is turned off on my Mac.Mauretania
possible duplicate of Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."Mauretania
In my case, _kCFStreamErrorCodeKey=57 matches state where request was sent to server, but client went offline before server sent response back to the client. Retrying on this kind of failure results in two identical records being created in server DB. Not sure if it's safe to assume that 57 means 'I sent whole request. Even if you go offline now, you can safely assume server will process the request'.Acetamide
R
92

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.

Revile answered 11/9, 2014 at 22:14 Comment(8)
This is, in fact, the right answer! I restarted XCode but somehow never thought of restarting the simulator. Yes, it works after restarting the simulator! Thank you!Mauretania
This happened to me when I was using the Simulator while on wireless, then switched to a wired connection. I even tried turning off wireless.Paapanen
Have any of you filed a radar about this? It's still happening with Xcode 6.1 and the iPhone 6 simulator.Osteoarthritis
@Revile as mentioned in the answers and comments to this SO question about the same issue, a few radars have already been filed.Osteoarthritis
Restart is a best policy, after honesty.Ritter
Wow. And this is why SO is awesome. I was going to start tearing apart my networking code. Thanks!Overt
Still happening in Xcode 6.2... Thank you stack overflow, and Ben-G for the quick answer!Jenniejennifer
Did you check in device? If you are uploading NSData to server using NSURLSessionUploadTask with defaultSessionConfiguration, it will returns same error when app is uploading data put app in back ground and lock device. It will return same error. Seems like app is losing internet connection when app is running in back ground. I also tried to update data from filePath with backgroundSessionConfigurationWithIdentifier and this time upload is continuously running in back ground until task got complete, once task complete it not start another task just wait until app again launch.Elzaelzevir
A
10

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

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!

Ava answered 9/12, 2015 at 14:26 Comment(3)
what where these unnecessary params in your code? I am facing similar issue.Olivero
I'm afraid I can't even remember what app I was working on back then... But if you only apply the necessary settings and parameters to your request it might help. Don't set the content-type if you're not sending an httpBody for exampleAva
This is dope! I tried many solutions but the issue was in the parameter that I was passing to request. Thank you for the hint!! :) @AvaLaurenlaurena
T
2

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.

  • 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!
Tap answered 12/6, 2015 at 2:37 Comment(0)
S
1

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.

[[VTNetworkingHelper sharedInstance] performRequestWithPath:@"Your url  " withAuth:YES forMethod:@"POST" withRequestJSONSerialized:NO withParams:params withCompletionHandler:^(VTNetworkResponse *response) {
            if (response.isSuccessful) {
    }else {
    }];
Sheasheaf answered 27/5, 2016 at 10:54 Comment(0)
E
0

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

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

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

Eurhythmics answered 27/8, 2015 at 5:49 Comment(0)
F
0

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 :

 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()
Factfinding answered 14/2, 2017 at 11:52 Comment(0)
D
-2

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

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

                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)
                                })
                            }
                 }
Demagnetize answered 25/8, 2017 at 6:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.