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)
Vikesh
  • 2,018
  • 6
  • 23
  • 33
  • 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? – quellish Sep 11 '14 at 21:43
  • @quellish The firewall is turned off on my Mac. – Vikesh Sep 11 '14 at 21:48
  • 3
    possible duplicate of [Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."](http://stackoverflow.com/questions/25372318/error-domain-nsurlerrordomain-code-1005-the-network-connection-was-lost) – Vikesh Sep 11 '14 at 21:48
  • 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'. – mixtly87 Oct 18 '17 at 22:29

7 Answers7

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.

Ben-G
  • 4,996
  • 27
  • 33
  • 5
    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! – Vikesh Sep 11 '14 at 23:48
  • 1
    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. – Paul Reedy Nov 03 '14 at 21:57
  • 5
    Have any of you filed a radar about this? It's still happening with Xcode 6.1 and the iPhone 6 simulator. – mluisbrown Dec 16 '14 at 13:26
  • @Ben-G as mentioned in the answers and comments to [this SO question](http://stackoverflow.com/q/25372318/368085) about the same issue, a few radars have already been filed. – mluisbrown Dec 17 '14 at 15:16
  • 1
    Restart is a best policy, after honesty. – Ans Dec 25 '14 at 09:35
  • Wow. And this is why SO is awesome. I was going to start tearing apart my networking code. Thanks! – Joshua Dance Mar 05 '15 at 05:31
  • Still happening in Xcode 6.2... Thank you stack overflow, and Ben-G for the quick answer! – staxim Apr 01 '15 at 23:38
  • 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. – Pratik Patel Oct 06 '15 at 05:45
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!

CMash
  • 1,987
  • 22
  • 35
  • what where these unnecessary params in your code? I am facing similar issue. – Tukkan Mar 07 '16 at 16:32
  • 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 example – CMash Mar 07 '16 at 16:34
  • 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!! :) @CMash – Sagar Unagar Sep 03 '19 at 10:00
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!
pcJmac
  • 21
  • 3
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 {
    }];
MuraliMohan
  • 1,063
  • 1
  • 11
  • 30
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!

Jayprakash Dubey
  • 35,723
  • 18
  • 170
  • 177
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()
Rahul Serodia
  • 419
  • 6
  • 13
-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)
                                })
                            }
                 }
Mehul
  • 3,033
  • 23
  • 37