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

28

292

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.

Henbit answered 18/8, 2014 at 21:28 Comment(7)
Any update ? It only happens on iOS 8 on Wifi for me, still trying to find a workaround.Farrar
#25995108Sawicki
Can anyone help me to solve my issue, almost the same issue but different error code, #26973322Pawpaw
Simply restart Xcode and Simulator.Variation
Sometimes it as lame as this:[enter link description here][1] [1]: #13543206 #megatardDarrondarrow
facing the same issue with iOS 10.0.1 and Xcode 8.Elfland
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.Sentience
E
411

Restarting the simulator fixed the issue for me.

Embosom answered 15/9, 2014 at 17:24 Comment(5)
What happens if this problem is on the device not the sim? Tried restarting the device, still same error.Interknit
@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).Fraction
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.Koss
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.Berryman
Resetting simulator didn't work for me. However starting Charles made issue to disappear. See https://mcmap.net/q/100130/-error-domain-nsurlerrordomain-code-1005-quot-the-network-connection-was-lost-quot which suggests using Charles. Very strange but works...Sou
F
257

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)
Fraction answered 23/9, 2014 at 13:54 Comment(31)
Here is an exemple project demonstrating the issue, a bug report have been submitted to Apple too. 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.Farrar
Is there anything we can do on the apps side to fix this if we have no access to the server side?Selfmastery
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.Insinuate
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.Rory
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.Threecornered
I can confirm @Kaili. I also have this issue on the device, when trying to access Amazon S3 buckets.Illtimed
@Dimillian77 do you have open radar that we can dup?Kitty
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.Capriccio
It works neither on the simulator nor on the device (actually it doesn't even work in Safari OSX…)Fraction
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.Spandrel
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.Echt
Tip: you can use the NSURLErrorNetworkConnectionLost constant instead of hard-coding -1005.Keratoid
@Arthur: Can you help me with below post #30513689 I am getting the same issue but on both iOS7 and 8 and it seems slightly different from this one.Peekaboo
Also even setting the connection close on server is not helping in this case.Peekaboo
@KenVanHoeylandt I can't believe this still has not been fixed... it is a really BIG issue with networking on iOS....Distill
if i send my request with a connection: closed header, will it affect my other requests without that header?Hannahhannan
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.Hammel
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.Haggadah
Any chance this is better with HTTP/2? (iOS 9+).Haggadah
@Farrar Your sample project is broken now, for both methods it returns 405Gann
This issue is still present on iOS 11.2.6.Liggins
iOS 11.3 and the issue is still there.. Anybody knows if there is an radar reported?Michaelmas
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 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 ?Maryn
@Arthur, what if the response does not contain Keep-Alive header, but I am still getting the same error?Winebaum
The same on iOS 13.3.Wilow
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.Krone
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.Promotive
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. github.com/firebase/firebase-ios-sdk/issues/2303Promotive
Sending "Connection": "Closed" helped me. Thank you.Impale
Hi @Maryn Did you managed to find a solution for this problem? Or any one else?Felid
iOS 16.5.1 issue is thereCodify
G
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)

Groce answered 29/10, 2014 at 6:54 Comment(1)
For iOS 14: Device > Erase All Contents and Settings...Autobiographical
D
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.

Dissimilarity answered 29/9, 2014 at 19:25 Comment(3)
I have this issue on a device too.Selfmastery
@darren Then it is not the issue that I was referring to. I suggest you file a radar.Dissimilarity
please include your radar ID so it makes filing duplicates easierHysterectomy
I
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).

Insinuate answered 19/8, 2014 at 1:29 Comment(9)
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 ?Henbit
No resolution have reported as a bug (18072300) will add comment about https working that is good information.Insinuate
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 messageStarter
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.Insinuate
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.Henbit
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).Oratorical
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 = "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;Farrar
I have this problem with Xcode 6.1.1 and iOS8.1 and https. Retrying 400 times does not seem to recover the situation.Mindy
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.Insinuate
C
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).

Callisthenics answered 26/9, 2014 at 19:15 Comment(6)
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 httpsDominions
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.Misadventure
Charles is a proxying tool that lets you watch traffic from your machine. Check charlesproxy.com for details. The Charles SSL cert can mess with the simulator's ability to make network requests.Callisthenics
@ColinTremblay I think your simulator/device is configured to use proxy. Removing proxy will also work.Sheers
Ridiculously, this worked for me too. Needed to have Charles open then reset the iOS Simulator settings.Brooklime
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...Amoritta
C
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!

Consistory answered 19/4, 2016 at 19:29 Comment(2)
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.Fluff
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 developer.apple.com/library/archive/qa/qa1941/_index.htmlLiebknecht
P
9

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

Powwow answered 3/2, 2015 at 9:29 Comment(1)
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.Adjoining
B
8

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

Barraza answered 30/1, 2019 at 19:3 Comment(0)
I
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;
     }

}
Incase answered 29/3, 2015 at 18:16 Comment(1)
Method 1 is helped me lot.. ThanksParticipial
R
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.

Rillings answered 6/2, 2016 at 8:44 Comment(1)
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.Christeenchristel
G
4

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;.

Gurtner answered 14/5, 2018 at 1:56 Comment(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.Alexine
S
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.

Selfmastery answered 30/9, 2014 at 12:58 Comment(2)
What is the MyAFHTTPRequestOperation class?Misadventure
It's just an AFHTTPRequestOperation subclass. I use it to predefine some stuff like timeout and authentication.Selfmastery
T
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.

Tranquil answered 8/4, 2015 at 12:44 Comment(0)
G
2

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

Gnat answered 30/11, 2015 at 15:15 Comment(0)
B
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.

Brogue answered 6/5, 2016 at 14:26 Comment(0)
D
2

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.

Daube answered 14/5, 2018 at 19:6 Comment(0)
B
2

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 :)

Breadth answered 1/11, 2018 at 12:39 Comment(0)
S
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.

Synsepalous answered 23/9, 2014 at 8:29 Comment(1)
The only relevant action in that list was restarting the simulator. Restarting Xcode and deleting Derived data is excessive.Dissimilarity
K
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.

Kura answered 9/12, 2015 at 20:15 Comment(0)
B
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"];
Barraza answered 5/3, 2016 at 0:20 Comment(0)
W
0

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

Wraith answered 4/6, 2015 at 13:1 Comment(1)
Could you please elaborate?Tananarive
C
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.

Chiasma answered 20/9, 2016 at 6:39 Comment(0)
S
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.

Seamy answered 3/4, 2018 at 7:0 Comment(0)
F
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

Fantasize answered 3/4, 2019 at 7:30 Comment(0)
E
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://mcmap.net/q/102149/-nsurlconnection-get-request-returns-1005-quot-the-network-connection-was-lost-quot and I changed my parameter and it works.

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

Hope this helps.

Eyelash answered 3/9, 2019 at 10:31 Comment(1)
A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link 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.Weanling
G
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'') 
Gladisgladney answered 14/7, 2020 at 12:19 Comment(0)
B
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
}
Bestow answered 9/11, 2022 at 20:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.