290

I have an application which works fine on Xcode6-Beta1 and Xcode6-Beta2 with both iOS7 and iOS8. But with Xcode6-Beta3, Beta4, Beta5 I'm facing network issues with iOS8 but everything works fine on iOS7. I get the error "The network connection was lost.". The error is as follows:

Error: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo=0x7ba8e5b0 {NSErrorFailingURLStringKey=, _kCFStreamErrorCodeKey=57, NSErrorFailingURLKey=, NSLocalizedDescription=The network connection was lost., _kCFStreamErrorDomainKey=1, NSUnderlyingError=0x7a6957e0 "The network connection was lost."}

I use AFNetworking 2.x and the following code snippet to make the network call:

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);
      }];

I tried NSURLSession but still receive the same error.

TenaciousJay
  • 6,750
  • 3
  • 45
  • 48
VoidStack
  • 3,038
  • 2
  • 14
  • 10
  • Any update ? It only happens on iOS 8 on Wifi for me, still trying to find a workaround. – Dimillian Sep 23 '14 at 09:13
  • http://stackoverflow.com/questions/25994608/swift-ios-api-controller-stopped-working/25995679#25995679 – Sam B Sep 24 '14 at 12:56
  • Can anyone help me to solve my issue, almost the same issue but different error code, http://stackoverflow.com/questions/26972822/error-error-domain-nsurlerrordomain-code-1001-the-request-timed-out – iYoung Nov 17 '14 at 12:39
  • Simply restart Xcode and Simulator. – Jayprakash Dubey Aug 19 '15 at 05:57
  • Sometimes it as lame as this:[enter link description here][1] [1]: http://stackoverflow.com/questions/13542706/iphone-simulator-cannot-connect-to-internet #megatard – Laser Hawk Sep 14 '15 at 21:27
  • 1
    facing the same issue with iOS 10.0.1 and Xcode 8. – Satheesh Oct 17 '16 at 18:36
  • 1
    I got this error this morning and fixed it just now with a simple and weird solution. The requested server address is wrong, there is no 4xx or 5xx status code returned, it just encountered this issue, not sure what exactly the root cause is. So, please confirm with the backend developers in your team, or you'll waste a few hours on it. – Itachi Dec 05 '16 at 14:29

28 Answers28

410

Restarting the simulator fixed the issue for me.

Collin
  • 6,720
  • 4
  • 26
  • 29
  • 3
    What happens if this problem is on the device not the sim? Tried restarting the device, still same error. – Sean Clark Dec 05 '14 at 18:41
  • 2
    @SeanClark: see the next answer: rebooting the simulator works because the OS needs to drop dead connection instead of trying to re-use them after they have been dropped by the server. To work around this issue, you can disable the Keep-alive mechanism on the server for the iOS clients, or, if you don't have access to the server, you can simply try again the same request when it fails (failure should make the OS drop the connection and a fresh one is instantiated when the retry is sent). – Arthur Dec 18 '14 at 10:09
  • I'm currently using Xcode 6.2 and what solved it was clicking on iOS Simulator > Reset Settings and Content. Once that finished I quit the simulator and rebuilt and ran my project... everything worked perfectly afterwards. – KingPolygon Jan 29 '15 at 08:05
  • It's worked for me to reset the simulator but only 10% of the time. I just got a new ISP and it runs kinda weird. This happens all the time now on simulator. Could be the network. – noobsmcgoobs Feb 11 '15 at 06:08
  • 1
    Resetting simulator didn't work for me. However starting Charles made issue to disappear. See http://stackoverflow.com/a/26066764/598057 which suggests using Charles. Very strange but works... – Stanislav Pankevich May 17 '16 at 11:50
255

We had this exact error and it turned out to be an issue with the underlying HTTP implementation of NSURLRequest:

As far as we can tell, when iOS 8/9/10/11 receive an HTTP response with a Keep-Alive header, it keeps this connection to re-use later (as it should), but it keeps it for more than the timeout parameter of the Keep-Alive header (it seems to always keep the connection alive for 30 seconds.) Then when a second request is sent by the app less than 30 seconds later, it tries to re-use a connection that might have been dropped by the server (if more than the real Keep-Alive has elapsed).

Here are the solutions we have found so far:

  • Increase the timeout parameter of the server above 30 seconds. It looks like iOS is always behaving as if the server will keep the connection open for 30 seconds regardless of the value provided in the Keep-Alive header. (This can be done for Apache by setting the KeepAliveTimeout option.
  • You can simply disable the keep alive mechanism for iOS clients based on the User-Agent of your app (e.g. for Apache: BrowserMatch "iOS 8\." nokeepalive in the mod file setenvif.conf)
  • If you don't have access to the server, you can try sending your requests with a Connection: close header: this will tell the server to drop the connection immediately and to respond without any keep alive headers. BUT at the moment, NSURLSession seems to override the Connection header when the requests are sent (we didn't test this solution extensively as we can tweak the Apache configuration)
Arthur
  • 4,093
  • 3
  • 17
  • 28
  • 8
    Here is an exemple project demonstrating the issue, a bug report have been submitted to Apple too. http://cl.ly/Xgkl/keep-alive-fail.zip Launch the project, click on the first post button (top on the screen), wait for 5 seconds, click on it again, error. – Dimillian Sep 23 '14 at 15:25
  • 3
    Is there anything we can do on the apps side to fix this if we have no access to the server side? – Darren Sep 24 '14 at 12:33
  • 6
    Keep-alive is bilateral. Clients will add an http header "Connection:Keep-Alive" by default, adding keep-alive parameters on the client requests may help; e.g. "Keep-Alive:max=1". Arthur's comment is very helpful but also indicates more than 1 problem in iOS8 simulator networking. I have to use https to get a connection as http fails before sending a request. – ptc Sep 24 '14 at 23:54
  • 5
    Hey guys, I'm having this exact same problem on the device. Is there a fix for this? There is no problem on iOS 7 though. – Andres C Oct 09 '14 at 14:08
  • I also have this problem on the device. I added the keep-alive suggestion to our NSURLSessionConfiguration and it is still failing with -1001 timeout. – Kaili Oct 17 '14 at 18:04
  • 2
    I can confirm @Kaili. I also have this issue on the device, when trying to access Amazon S3 buckets. – Leandros Nov 19 '14 at 10:58
  • 1
    @Dimillian77 do you have open radar that we can dup? – an0 Nov 24 '14 at 16:41
  • Do you know if the Keep-Alive issue is only on the simulator or also on the device? I'm getting the -1005 error frequently, but only on the simulator, never on the device. – mluisbrown Dec 17 '14 at 15:14
  • 1
    It works neither on the simulator nor on the device (actually it doesn't even work in Safari OSX…) – Arthur Dec 18 '14 at 10:01
  • I am having the same problem with iOS 8 and wi-fi connections, what i did is set [request setTimeoutInterval:30]; I can't tell if it is the right way to do it, but so far i haven't had any problems. – Fernando Santiago Feb 07 '15 at 01:56
  • 3
    Another client side workaround (for those who can't or won't change their server configuration) is check if the NSError object of the failure block has code -1005, which indicates this issue has occurred. You could then simply retry the network operation, as this time iOS will reconnect. I also added a retry counter to make sure this workaround doesn't end in an infinite loop. – Rachid Finge Jr Mar 08 '15 at 16:59
  • 10
    Tip: you can use the `NSURLErrorNetworkConnectionLost` constant instead of hard-coding `-1005`. – Vincent Tourraine Apr 09 '15 at 09:47
  • @Arthur: Can you help me with below post http://stackoverflow.com/questions/30513189/getting-continous-the-operation-couldn-t-be-completed-after-recursive-post-cal I am getting the same issue but on both iOS7 and 8 and it seems slightly different from this one. – Arun Gupta May 28 '15 at 17:50
  • Also even setting the connection close on server is not helping in this case. – Arun Gupta May 29 '15 at 06:41
  • 1
    @KenVanHoeylandt I can't believe this still has not been fixed... it is a really BIG issue with networking on iOS.... – Oscar Gomez Sep 10 '15 at 19:41
  • if i send my request with a connection: closed header, will it affect my other requests without that header? – Happiehappie Apr 14 '16 at 11:20
  • 3
    I had the same problem but right into a macOS app (not an iOS simulator). And the problem disappeared once I changed the `TIMEOUT` value from 30 to 60 sec on my server. – onekiloparsec Sep 09 '16 at 14:34
  • I increased the timeout from 5 to 35 seconds in my Apache 2.4 configuration and it doesn't seem to have helped at all. – Hamish Moffatt May 16 '17 at 05:11
  • Any chance this is better with HTTP/2? (iOS 9+). – Hamish Moffatt May 16 '17 at 05:13
  • @Dimillian Your sample project is broken now, for both methods it returns 405 – Neil Galiaskarov Jul 22 '17 at 10:57
  • 6
    This issue is still present on iOS 11.2.6. – Makalele Mar 15 '18 at 11:44
  • 1
    iOS 11.3 and the issue is still there.. Anybody knows if there is an radar reported? – Miroslav Kovac Apr 11 '18 at 12:33
  • Re: NSURLConnection & error -1005 We have this issue when accessing a web service based on a server in Australia by a customer in the UK. We have reproduced this by using a VPN in the UK to access our Web service. The error can also be found when downloading large files from a static URL based in Australia. (For example http://speedcheck.cdn.on.net/100meg.test) When using NSURLConnection with delegate callabacks the download proceeds for a long time sendng data back until it eventually errors out with an error -1005. Does anyone have any solutions ? – PhilB Apr 20 '18 at 06:02
  • 1
    @Arthur, what if the response does not contain Keep-Alive header, but I am still getting the same error? – o15a3d4l11s2 Sep 16 '18 at 10:34
  • 1
    The same on iOS 13.3. – IvanPavliuk Dec 17 '19 at 08:31
  • I met this same issue on iOS 13.3 for real device. In a learning course which involves TMDB API, to login/authenticate outside the app via Safari and get back to app. – Zhou Haibo Jan 06 '20 at 17:41
  • having same problem on 13.4.1. If I shoot 2 or 3 requests off to the server before sending the one I care about, then the one I care about always works. Weird. – zumzum Jun 01 '20 at 01:59
  • This is what I am facing exactly. Seems like a delay solves the issue, and would explain why sending two or three requests before the one I actually want to make sure works would solve the issue for me. The requests I send before the one I care about, implicitly create a delay. This GitHub page puts a delay and solves the issue. https://github.com/firebase/firebase-ios-sdk/issues/2303 – zumzum Jun 01 '20 at 02:25
  • Sending "Connection": "Closed" helped me. Thank you. – Luzo Sep 07 '21 at 12:24
  • Hi @PhilB Did you managed to find a solution for this problem? Or any one else? – Angels Oct 26 '22 at 08:32
  • iOS 16.5.1 issue is there – Async- Aug 29 '23 at 09:25
45

For mine, Resetting content and settings of Simulator works. To reset the simulator follow the steps:

iOS Simulator -> Reset Content and Settings -> Press Reset (on the warning which will come)

Manab Kumar Mal
  • 20,788
  • 5
  • 31
  • 43
29

The iOS 8.0 simulator runtime has a bug whereby if your network configuration changes while the simulated device is booted, higher level APIs (eg: CFNetwork) in the simulated runtime will think that it has lost network connectivity. Currently, the advised workaround is to simply reboot the simulated device when your network configuration changes.

If you are impacted by this issue, please file additional duplicate radars at http://bugreport.apple.com to get it increased priority.

If you see this issue without having changed network configurations, then that is not a known bug, and you should definitely file a radar, indicating that the issue is not the known network-configuration-changed bug.

Jeremy Huddleston Sequoia
  • 22,938
  • 5
  • 78
  • 86
11

Also have a problem with beta 5 and AFNetworking 1.3 when running on iOS 8 simulator that results in a connection error:

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

The same code works fine on iOS 7 and 7.1 simulators and my debugging proxy shows that the failure occurs before a connection is actually attempted (i.e. no requests logged).

I have tracked the failure to NSURLConnection and reported bug to Apple. See line 5 in attached image:

NSURLConnection client delegate did fail error.

Changing to use https allows connection from iOS 8 simulators albeit with intermittent errors.

Problem is still present in Xcode 6.01 (gm).

pkamb
  • 33,281
  • 23
  • 160
  • 191
ptc
  • 734
  • 5
  • 11
  • I see the same problem with NSURLSession and NSURLConnection, thats rules out the problem with AFNetworking. Also I found it works with https and failing with http. I still couldn't find any solution, did you got any resolution ? – VoidStack Aug 25 '14 at 18:11
  • No resolution have reported as a bug (18072300) will add comment about https working that is good information. – ptc Aug 26 '14 at 21:04
  • could you paste the bug link here? Thanks because I think I have the same problem but I only use the NSURLConnection (and delegates) but I get the same error message – szuniverse Sep 03 '14 at 19:59
  • Not able to share Apple bug report. Still open and still present in XCODE 6 beta 7. If you file a bug report also that will help with priority. – ptc Sep 04 '14 at 21:28
  • Looks like this issue is on iOS simulator and I tired with actual device it works fine. Further debugging I found problem is about port on iOS simulator, https port 443 works fine and I was using 8080 for http it used to fail. I tried using other port(s) and able to make http call on iOS simulator. Looks like bug in beta Xcode 6, need to wait for stable Xcode 6. – VoidStack Sep 05 '14 at 22:53
  • I believe the issue is not specific to the simulator (because I can reproduce the problem on a real device), but specific to iOS 8.0 (because I can't reproduce it on iOS 7.0). – spybart Sep 12 '14 at 03:45
  • I have the exact same problems on both iOS 8 simulator and devices. Some of my POST (and only POST request) got this error. The userInfo is NSErrorFailingURLStringKey = "https://rcapi.glose.com/oauth/token"; NSUnderlyingError = "Error Domain=kCFErrorDomainCFNetwork Code=-1005 \"The operation couldn\U2019t be completed. (kCFErrorDomainCFNetwork error -1005.)\" UserInfo=0x7a9e1880 {_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4}"; "_kCFStreamErrorCodeKey" = "-4"; "_kCFStreamErrorDomainKey" = 4; – Dimillian Sep 18 '14 at 10:07
  • I have this problem with Xcode 6.1.1 and iOS8.1 and https. Retrying 400 times does not seem to recover the situation. – ghr Mar 30 '15 at 05:37
  • The problem is still present in Xcode 6.2 and 6.3 beta 4. I have personally not had a problem with any actual device. The problem is with the simulator and for me only affects sites that do not support SSL. Installing the Charles root certificate for the simulator and running Charles as an SSL proxy allows me to connect to all sites required in my apps from the simulator. – ptc Mar 31 '15 at 06:37
10

Opening Charles resolved the issue for me, which seems very strange...

Charles is an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet. This includes requests, responses and the HTTP headers (which contain the cookies and caching information).

pkamb
  • 33,281
  • 23
  • 160
  • 191
Colin Tremblay
  • 357
  • 1
  • 9
  • 1
    This works for me too, I think because charles uses a ssl certificate to proxy the sumulator requests it does a similar trick to using https – thisispete Oct 28 '14 at 19:07
  • 1
    This works for me everytime! Have tried it 30 times and it works 30 out of 30. I thought it was fluke, but good to know it just isn't me. – jdog Nov 06 '14 at 06:11
  • 2
    Charles is a proxying tool that lets you watch traffic from your machine. Check http://www.charlesproxy.com for details. The Charles SSL cert can mess with the simulator's ability to make network requests. – Colin Tremblay Jun 15 '15 at 19:56
  • @ColinTremblay I think your simulator/device is configured to use proxy. Removing proxy will also work. – bikram990 Jul 13 '16 at 06:51
  • Ridiculously, this worked for me too. Needed to have Charles open then reset the iOS Simulator settings. – Matt Andrews Aug 09 '16 at 10:20
  • Can it also mess with physical device? Because I have this issue on a real device. I'm not running Charles on my mac, nor on my device. I had it before... – mfaani Nov 20 '19 at 15:25
10

I was experiencing this problem while using Alamofire. My mistake was that I was sending an empty dictionary [:] for the parameters on a GET request, rather than sending nil parameters.

Hope this helps!

yujean
  • 795
  • 8
  • 14
  • GET and POST with empty body dictionary [:] will cause this error randomly. I am using Python Flask for the backend REST APIs this may be useful too. – Mahmoud Fayez Sep 19 '18 at 18:23
  • Why would that cause a NSURLErrorNetworkConnectionLost error? "This error means that the underlying TCP connection that’s carrying the HTTP request disconnected while the HTTP request was in progress”. See https://developer.apple.com/library/archive/qa/qa1941/_index.html – Max MacLeod Nov 24 '22 at 12:28
9

what solved the problem for me was to restart simulator ,and reset content and settings.

m.eldehairy
  • 695
  • 8
  • 10
  • It also helps to kill the app before the simulator reset and to restart the Mac. I often change places with different wifi spots and this is a procedure that fixes the issue for me. – Vladimír Slavík Oct 29 '15 at 10:18
6

See pjebs comment on Jan 5 on Github.

Method1 :

if (error.code == -1005)
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

        dispatch_group_t downloadGroup = dispatch_group_create();
        dispatch_group_enter(downloadGroup);
        dispatch_group_wait(downloadGroup, dispatch_time(DISPATCH_TIME_NOW, 5000000000)); // Wait 5 seconds before trying again.
        dispatch_group_leave(downloadGroup);
        dispatch_async(dispatch_get_main_queue(), ^{
            //Main Queue stuff here
            [self redoRequest]; //Redo the function that made the Request.
        });
    });

    return;
}

Also some suggests to re-connect to the site,

i.e. Firing the POST request TWICE

Solution: Use a method to do connection to the site, return (id), if the network connection was lost, return to use the same method.

Method 2

-(id) connectionSitePost:(NSString *) postSender Url:(NSString *) URL {
     // here set NSMutableURLRequest =>  Request

    NSHTTPURLResponse *UrlResponse = nil;
    NSData *ResponseData = [[NSData alloc] init];

    ResponseData = [NSURLConnection sendSynchronousRequest:Request returningResponse:&UrlResponse error:&ErrorReturn];

     if ([UrlResponse statusCode] != 200) {

          if ([UrlResponse statusCode] == 0) {

                  /**** here re-use method ****/
                  return [self connectionSitePost: postSender Url: URL];
          }

     } else {
          return ResponseData;
     }

}
pkamb
  • 33,281
  • 23
  • 160
  • 191
HDdeveloper
  • 4,396
  • 6
  • 40
  • 65
6

On 2017-01-25 Apple released a technical Q&A regarding this error:

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

Community
  • 1
  • 1
pkamb
  • 33,281
  • 23
  • 160
  • 191
5

I was getting this error as well, but on actual devices rather than the simulator. We noticed the error when accessing our heroku backend on HTTPS (gunicorn server), and doing POSTS with large bodys (anything over 64Kb). We use HTTP Basic Auth for authentication, and noticed the error was resolved by NOT using the didReceiveChallenge: delegate method on NSURLSession, but rather baking in the Authentication into the original request header via adding Authentiation: Basic <Base64Encoded UserName:Password>. This prevents the necessary 401 to trigger the didReceiveChallenge: delegate message, and the subsequent network connection lost.

rvijay007
  • 1,357
  • 12
  • 20
  • Thank you so much for your valuable comment. You are right if I upload below 64 kb image's base64 string it will uploaded successfully. – Vinayak Bhor Jun 22 '18 at 15:02
3

I had the same problem. I don't know how AFNetworking implements https request, but the reason for me is the NSURLSession's cache problem.

After my application tracking back from safari and then post a http request, "http load failed 1005" error will appear. If I stop using "[NSURLSession sharedSession]", but to use a configurable NSURLSession instance to call "dataTaskWithRequest:" method as follow, the problem is solved.

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
config.URLCache = nil;
self.session = [NSURLSession sessionWithConfiguration:config];

Just remember to set config.URLCache = nil;.

Jia Xiao
  • 667
  • 6
  • 5
  • 1
    I think all those restarting device/simulator or resetting data should look into this answer. To me all of their actions seems to clear cache which actually fixes the issue. So its probably URL Cache issue. I am going to test it now. – Kamran Khan Jun 04 '18 at 09:13
2

I have this issue also, running on an iOS 8 device. It is detailed some more here and seems to be a case of iOS trying to use connections that have already timed out. My issue isn't the same as the Keep-Alive problem explained in that link, however it seems to be the same end result.

I have corrected my problem by running a recursive block whenever I receive an error -1005 and this makes the connection eventually get through even though sometimes the recursion can loop for 100+ times before the connection works, however it only adds a mere second onto run times and I bet that is just the time it takes the debugger to print the NSLog's for me.

Here's how I run a recursive block with AFNetworking: Add this code to your connection class file

// From Mike Ash's recursive block fixed-point-combinator strategy https://gist.github.com/1254684
dispatch_block_t recursiveBlockVehicle(void (^block)(dispatch_block_t recurse))
{
    // assuming ARC, so no explicit copy
    return ^{ block(recursiveBlockVehicle(block)); };
}
typedef void (^OneParameterBlock)(id parameter);
OneParameterBlock recursiveOneParameterBlockVehicle(void (^block)(OneParameterBlock recurse, id parameter))
{
    return ^(id parameter){ block(recursiveOneParameterBlockVehicle(block), parameter); };
}

Then use it likes this:

+ (void)runOperationWithURLPath:(NSString *)urlPath
            andStringDataToSend:(NSString *)stringData
                    withTimeOut:(NSString *)timeOut
     completionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    OneParameterBlock run = recursiveOneParameterBlockVehicle(^(OneParameterBlock recurse, id parameter) {
        // Put the request operation here that you want to keep trying
        NSNumber *offset = parameter;
        NSLog(@"--------------- Attempt number: %@ ---------------", offset);

        MyAFHTTPRequestOperation *operation =
            [[MyAFHTTPRequestOperation alloc] initWithURLPath:urlPath
            andStringDataToSend:stringData
            withTimeOut:timeOut];

        [operation setCompletionBlockWithSuccess:
            ^(AFHTTPRequestOperation *operation, id responseObject) {
                success(operation, responseObject);
            }
            failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
                if (error.code == -1005) {
                    if (offset.intValue >= numberOfRetryAttempts) {
                        // Tried too many times, so fail
                        NSLog(@"Error during connection: %@",error.description);
                        failure(operation2, error);
                    } else {
                        // Failed because of an iOS bug using timed out connections, so try again
                        recurse(@(offset.intValue+1));
                    }
                } else {
                    NSLog(@"Error during connection: %@",error.description);
                    failure(operation2, error);
                }
            }];
        [[NSOperationQueue mainQueue] addOperation:operation];
    });
    run(@0);
}

You'll see that I use a AFHTTPRequestOperation subclass but add your own request code. The important part is calling recurse(@offset.intValue+1)); to make the block be called again.

JOM
  • 8,139
  • 6
  • 78
  • 111
Darren
  • 10,182
  • 20
  • 95
  • 162
2

If the problem is occurring on a device, check if traffic is going through a proxy (Settings > Wi-Fi > (info) > HTTP Proxy). I had my device setup to use with Charles, but forgot about the proxy. Seems that without Charles actually running this error occurs.

David James
  • 2,430
  • 1
  • 26
  • 35
2

I was connecting via a VPN. Disabling the VPN solved the problem.

alpere
  • 1,079
  • 17
  • 26
2

I had same problem. Solution was simple, I've set HTTPBody, but haven't set HTTPMethod to POST. After fixing this, everything was fine.

Timur Bernikovich
  • 5,660
  • 4
  • 45
  • 58
1

I had to exit XCode, delete DerivedData folder contents (~/Library/Developer/Xcode/DerivedData or /Library/Developer/Xcode/DerivedData) and exit simulator to make this work.

abinop
  • 3,153
  • 5
  • 32
  • 46
1

If anyone is getting this error while uploading files to a backend server, make sure the receiving server has a maximum content size that is allowable for your media. In my case, NGINX required a higher client_max_body_size. NGINX would reject the request before the uploading was done so no error code came back.

Raymond26
  • 590
  • 1
  • 7
  • 14
1

I was hitting this error when passing an NSURLRequest to an NSURLSession without setting the request's HTTPMethod.

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

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

Add the HTTPMethod, though, and the connection works fine

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlComponents.URL];
[request setHTTPMethod:@"PUT"];
pkamb
  • 33,281
  • 23
  • 160
  • 191
1

I was facing the same issue, I have enabled Network Link Conditioner for slow network testing for the app. That was creating this error some times, When i have disabled it from Settings > Developer > Network Link Conditioner, it solved my problem.

enter image description here

Hope this help someone.

Dhaval Bhimani
  • 980
  • 1
  • 13
  • 24
1

On top of all the answers i found one nice solution. Actually The issue related to network connection fail for iOS 12 onword is because there is a bug in the iOS 12.0 onword. And it Yet to resolved. I had gone through the git hub community for AFNetworking related issue when app came from background and tries to do network call and fails on connection establish. I spend 3 days on this and tries many things to get to the root cause for this and found nothing. Finally i got some light in the dark when i red this blog https://github.com/AFNetworking/AFNetworking/issues/4279

It is saying that there is a bug in the iOS 12. Basically you cannot expect a network call to ever complete if the app os not in foreground. And due to this bug the network calls get dropped and we get network fails in logs.

My best suggestion to you is provide some delay when your app are coming from background to foreground and there is network call. Make that network call in the dispatch async with some delay. You'll never get network call drop or connection loss.

Do not wait for Apple to let this issue solve for iOS 12 as its still yet to fix. You may go with this workaround by providing some delay for your network request being its NSURLConnection, NSURLSession or AFNetworking or ALAMOFIRE. Cheers :)

Shankar Aware
  • 128
  • 1
  • 11
0

Got the issue for months, and finally discovered that when we disable DNSSEC on our api domain, everything was ok.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
0

I was having this issue for the following reason.

TLDR: Check if you are sending a GET request that should be sending the parameters on the url instead of on the NSURLRequest's HTTBody property.

==================================================

I had mounted a network abstraction on my app, and it was working pretty well for all my requests.

I added a new request to another web service (not my own) and it started throwing me this error.

I went to a playground and started from the ground up building a barebones request, and it worked. So I started moving closer to my abstraction until I found the cause.

My abstraction implementation had a bug: I was sending a request that was supposed to send parameters encoded in the url and I was also filling the NSURLRequest's HTTBody property with the query parameters as well. As soon as I removed the HTTPBody it worked.

Nuno Gonçalves
  • 6,202
  • 7
  • 46
  • 66
0

Whenever got error -1005 then need to call API Again.

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);
      if (error.code == -1005) {
          // Call method again... 
       }
  }];

You need to Add your code to call function again. MakeSure that you were call method once otherwise its call recursive loop.

Piyush
  • 1,156
  • 12
  • 20
0

I faced the same issue while calling using my company's server from iOS 12 app with a physical device. The problem was that the server hard disk was full. Freeing space in the server solved the problem.

I found the same error in another situation I think due to a timeout not parametrizable through the standard Networking API provided by Apple (URLSession.timeoutIntervalForRequest and URLSession.timeoutIntervalForResource). Even there.. made server answer faster solved the problem

Mattia Ducci
  • 412
  • 6
  • 10
0

This might be a problem of the parameter that you are passing to request body. I was also facing the same issue. But then I came across CMash's answer here https://stackoverflow.com/a/34181221/5867445 and I changed my parameter and it works.

Issue in a parameter that I was passing is about String Encoding.

Hope this helps.

Sagar Unagar
  • 201
  • 1
  • 6
  • 18
  • A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259/165483) so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted.](//stackoverflow.com/help/deleted-answers) – Samuel Liew Sep 04 '19 at 10:26
0

My problem was on the server. I was using Python's BaseHTTPRequestHandler class and I wasn't sending a body in the response. My problem was solved when I put an empty body like the following.

def do_POST(self):
    content_len = int(self.headers.get('Content-Length'))
    post_body = self.rfile.read(content_len)
    msg_string = post_body.decode("utf-8")
    msg_json = json.loads(msg_string)
    self.send_response(200)
    self.end_headers() #this and the following lines were missing
    self.wfile.write(b'') 
Laura Corssac
  • 1,217
  • 1
  • 13
  • 23
0

I had the same issue, the problem was bug of Alomofire and NSUrlSession. When you returning back to app from safari or email you need to wait nearly 2 seconds to do you network response via Alamofire

 DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
       Your network response
}
Artsem Sharubin
  • 388
  • 3
  • 10