Afnetworking: The operation couldn’t be completed only in Wifi with POST method under iOS 8

Created on 23 Sep 2014  Â·  94Comments  Â·  Source: AFNetworking/AFNetworking

I'm having some very weird issues with iOS 8. It never happens under iOS 7, and it only happens on iOS 8 on Wifi (tested with 3 different network) but not on cellular network.
Around 2/3 of my POST Request fail, with an "Operation couldn't be completed" error.

I tried debugging it, server side, client side. It seems like the failing request never leave the iPhone, it goes directly to the didFail delegate with an error.

Here is the full error message

Error Domain=NSURLErrorDomain Code=-1005 "The operation couldn’t be completed. (NSURLErrorDomain error -1005.)" UserInfo=0x7feb814388a0 {NSErrorFailingURLStringKey=[removeURL], NSErrorFailingURLKey=[removedURL], _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x7feb81456750 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1005.)"

I think this SO question is kinda linked, it sound like it's a mix between the configuration of the application, AFNetworking and some iOS weirdness... http://stackoverflow.com/questions/25372318/error-domain-nsurlerrordomain-code-1005-the-network-connection-was-lost

Most helpful comment

Just an update, this is still an issue on iOS 11.3.

All 94 comments

This is an issue with the underlying HTTP implementation of NSURL.

As far as we can tell, when iOS 8 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 and then when a second request comes it tries to re-use a connection that has been dropped by the server.

As a monkey patch if anybody else is having this issue, you can add BrowserMatch "^iOS/8\." nokeepalive (with the correct user agent of course) somewhere in your Apache server config (This is nowhere near perfect but makes things work until Apple patches iOS8).

This issue can be closed

For workarounds, see http://stackoverflow.com/a/25996971/2258249

After more testing with @arthurdarcet we've submitted the bug to Apple, AFNetworking can't do anything, but is impacted by this bug.

@mattt Here is a sample project for you to test: http://cl.ly/Xgkl

On the first post button, click on it, see the server response with our headers. Wait 5 seconds or more, click on it again. Boom error.

This problem is also causing problems for my app on iOS 8. I'm not holding out for an Apple fix anytime soon.

Is there any way from the apps side that we can force a nokeepalive? Maybe intercepting the response, or is that point already too late?

Thanks

@ddaddy Intercepting the first response and removing the keep alive header might be a good idea, unfortunately it'll already be too late.

If you don't have direct control over the server, it's a real pain, if you find any solution it would be awesome. In our case we control the server so we was able to change the headers for iOS 8.

I really hope Apple will fix it asap.

@ddaddy A client side solution would be to keep a timer running, and if a new POST request is emitted after the keep-alive has expired (you know it from the previous request response headers), then fire it twice. It's a very dirty solution, but it should works in some cases.

Edit: We also noticed that iOS expire the connection after around 30 seconds, so you also need to take that into account.

@Dimillian Thanks, i'll look into that. Would the second attempt not just use the exact same connection? Or does it close it once it's failed?

I'm no expert in in objective-c, but I think nothing can be done on the client side: the HTTP stack of iOS needs to intercept connection at a very low level to be able to re-use it. And I don't see why it would expose a way to deactivate Keep-Alives (if the server send a Keep-Alive, and your client supports it, no reason not to use it).

If you don't have access to the server, I would try adding Mozilla/2 somewhere in your user-agent, since Netscape 2 didn't support Keep-Alive, the server might have a configuration option activated to disable Keep-Alive for this user-agent (it's not that long a shot, it's in the default Apache2 configuration)

(yes, Apple HTTP stack is at the level of Netscape 2.02, circa 95…)

@ddaddy As per our tests, if it fail once, the next one will be on a new connection.

@arthurdarcet Thanks, but that didn't work. The actual server i'm using is built into a home router so i'm not sure how it'll be configured.

@Dimillian I've just tested issuing a second request operation when the first fails and it fails also so it must be using the same connection again.

Are you sure you are having the exact same problem?
Do you have:

  • First request is always OK and respond with Keep-Alive: … timeout=X …
  • Another request after _less_ than X seconds is OK
  • Waiting at least X seconds makes the next request fail
  • First request after the failure is OK

If you don't have the same comportement, you are probably experiencing another issue, probably something to do with your network.

I've just checked the returned headers, and there's no keep-alive at all:

"Cache-Control" = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, no-cache";
Connection = close;
"Content-Type" = "text/html";
Date = "Wed, 24 Sep 2014 14:07:33 GMT";
Expires = 0;
Pragma = "no-cache, no-cache";
Server = httpd;

However i'm pretty sure i'm having a related issue. I am hitting the server with 3 consecutive requests, and normally the 3rd one will fail with the error The network connection was lost.
I've just added a loop to one of my requests and I can now get it to work every time by sending the same request after it fails, however it doesn't always work after sending the 2nd request. On one occasion it failed 11 times then went through fine, so it must be a timing issue.

@ddaddy Yeah, look like it's not exactly the same issue. Honestly, could be an iOS 8 bug, but could be anything else too, maybe your server is falling. Do you have the exact same error as in my first post? And it's a POST request right? Could you try over cellular too (the issue is only occurring over WIFI for me).

Do you have access to some server logs ? Does this appear only on POSTs or
also on GETs ?

2014-09-24 16:11 GMT+02:00 ddaddy [email protected]:

I've just checked the returned headers, and there's no keep-alive at all:

"Cache-Control" = "no-store, no-cache, must-revalidate, post-check=0,
pre-check=0, no-cache";
Connection = close;
"Content-Type" = "text/html";
Date = "Wed, 24 Sep 2014 14:07:33 GMT";
Expires = 0;
Pragma = "no-cache, no-cache";
Server = httpd;

However i'm pretty sure i'm having a related issue. I am hitting the
server with 3 consecutive requests, and normally the 3rd one will fail with
the error The network connection was lost.
I've just added a loop to one of my requests and I can now get it to work
every time by sending the same request after it fails, however it doesn't
always work after sending the 2nd request. On one occasion it failed 11
times then went through fine, so it must be a timing issue.

—
Reply to this email directly or view it on GitHub
https://github.com/AFNetworking/AFNetworking/issues/2314#issuecomment-56674988
.

@Dimillian Yes it's a POST request. Same error code Error during connection: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo=0x1782e2980 {NSUnderlyingError=0x178240ab0 "The network connection was lost.", NSErrorFailingURLStringKey=[url removed], NSErrorFailingURLKey=[url removed], _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=The network connection was lost.} and also fails over cellular.

It's only started happening since iOS 8.

@arthurdarcet I've only tried using POST sorry as I need to send some params with it. I'll have a look if I can get at server logs, although the speed the failures happen, I don't think the phone is even attempting to communicate.

If I am trying make multipart service I am getting this problem Error "Domain=NSURLErrorDomain Code=-1001 "The operation couldn’t be completed. (NSURLErrorDomain error -1001.)"

But same code works from Xcode 5.x.x.

we too facing the same issue and we did the change suggested by @arthurdarcet . Hope apple fixes it soon.

@linganaidu Please fill a radar too, I really hope Apple is aware of this issue, this is too big to not be fixed asap.

@Dimillian looks like some one has already opened a radar for this.You want m open a new again? I have never fill radar before, can u help m out.

@linganaidu I did a radar so it's ok, plus it's not an easy one to report and detail, so it's maybe not a good first radar :)

@Dimillian Thanks. Please update us if you get any response form apple.

I have just tested this with the new iOS 8.0.2 and the problem still exists.
I have managed to get it working client side by using a recurring block whenever an error -1005 is returned.

did anyone test in 8.1 beta 2?

We tested this on on 8.1 beta 2 and the problem still persisted
We overcame it by making our https calls in sequence instead of asynchronous

Little background into issues faced
Ours is a Hybrid App and there are 6 asynchronous calls simultaneously . everything worked fine till iOS 7 but this stopped working in iOS8 using https calls
Please note that on http it worked fine even on iOS8

When Charles was used to sniff the results everything worked fine even on iOS8.This was very strange though

Then taking a cue from one of the comments in this issue , we made our calls synchronous and everything worked well . This is has slowed down the App a bit but at-least there's a workaround till there's a fix available for it.
Does anyone know of the bug raised with Apple in this regard.

@rkmahajan I sent a radar to Apple in September, still no acknowledgement on their part. So you can submit it too. Really sad it still present in iOS 8.1

For the workaround "BrowserMatch "^iOS/8." nokeepalive", what is the best way to disable keepalive in my nginx conf ?

I tried without success :

keepalive_disable safari;
keepalive_timeout 0;

I can always see :
Connection = "keep-alive";
in my HTTP response header.

I meet the same issue even I disabled the keep-alive.... the connection header is connection = close but i still can fire the issue randomly... Anyone has the same issue?

I am getting -1001 for GET request on iOS 8.0. Would anyone suggest something on this issue?

This happens to us as well. We haven't gotten any data (because we're not allowed to track) on what views it happens but we got both concurrent and serial requests.

Us too now.

@iosengineer Want to chat about this later? We might have some ideas on this.

Unfortunately, this but it's a low-priority issue for me at the moment. I've worked with Keep-Alive issues in the past so I have some ideas that might help but I'm also flat out (what's new?).

@iosengineer @seivan Were you able to come up with a solution to this either via nginx conf or client side?

@mverderese As mentioned in one of my previous comments: for Apache something along the lines of BrowserMatch "^iOS/8\." nokeepalive works ; and you can probably adapt that for nginx.

Client side you should also be able to send a Connection: Close header that should fix the issue.

@mattt any update on this?

Im having this issue with a GET request. But Im not sure if its my code. I've posted the issue here:

https://groups.google.com/forum/#!topic/parse-developers/XbL4AkKbEv4

http://stackoverflow.com/questions/27079603/afnetworking-network-connection-lost

Im not sure its an iOS8 specific in my case because Ive tried using ios7 as deployment and i get the same issue.

@quique123 this issue has a very generic error message but very specific causes.
If it's not working on iOS7, then your problem has nothing to do with this issuse.
Same if GET requests are impacted

@arthurdarcet said: "Client side you should also be able to send a Connection: Close header that should fix the issue."

If I understand it correctly, "Connection: Close" only affect the following requests. It means I can not only set this header for POST requests even thought this bug only affects POST requests, because if a GET request preceding a POST requests builds a persistent connection the POST request may still reuse this connection even with "Connection: Close" header set and trigger this bug, right? So I have to set "Connection: Close" for all kinds of requests?

AFAIK, it's not a problem with iOS 8 - it's with the iOS 8 SDK or shipped libraries, so anything built against the 8 SDK seems to be affected. 

Connection close should work because this issue only affects subsequent requests made on the same keep-alive connection.

I'm time poor at the moment or else I'd do a write up on it.

—
Sent from Mailbox

On Tue, Nov 25, 2014 at 4:25 AM, Ling Wang [email protected]
wrote:

@arthurdarcet said: "Client side you should also be able to send a Connection: Close header that should fix the issue."

If I understand it correctly, "Connection: Close" only affect the following requests. It means I can not only set this header for POST requests even thought this bug only affects POST requests, because if a GET request preceding a POST requests builds a persistent connection the POST request may still reuse this connection even with "Connection: Close" header set and trigger this bug, right? So I have to set "Connection: Close" for all kinds of requests?

Reply to this email directly or view it on GitHub:
https://github.com/AFNetworking/AFNetworking/issues/2314#issuecomment-64229696

Also, not specific to POST requests.

—
Sent from Mailbox

On Tue, Nov 25, 2014 at 4:25 AM, Ling Wang [email protected]
wrote:

@arthurdarcet said: "Client side you should also be able to send a Connection: Close header that should fix the issue."

If I understand it correctly, "Connection: Close" only affect the following requests. It means I can not only set this header for POST requests even thought this bug only affects POST requests, because if a GET request preceding a POST requests builds a persistent connection the POST request may still reuse this connection even with "Connection: Close" header set and trigger this bug, right? So I have to set "Connection: Close" for all kinds of requests?

Reply to this email directly or view it on GitHub:
https://github.com/AFNetworking/AFNetworking/issues/2314#issuecomment-64229696

@iosengineer so I need to set "Connection: Close" for all kinds of requests not only POST requests, right?

Yes. It should work. I haven't tested it. You're essentially overriding the server's keep-alive option on the client side but all client requests have to understand that. If they (at, say, a busted framework level) think they can reuse a connection for another request then it won't work.

Keep-Alive works by a two-part agreement. The server sends a Keep-Alive header and the client has to send it back. I haven't verified this yet, but if I'm right in that the client is not returning the header then I'm not sure at what level on the client side it understands that keep-alive is enabled or disabled (and whether that's broken or not).

If I had a moment, I'd Charles it and check the header dialog.

—
Sent from Mailbox

On Tue, Nov 25, 2014 at 7:54 AM, Ling Wang [email protected]
wrote:

@iosengineer so I need to set "Connection: Close" for all kinds of requests not only POST requests, right?

Reply to this email directly or view it on GitHub:
https://github.com/AFNetworking/AFNetworking/issues/2314#issuecomment-64262578

@arthurdarcet I just read that it has to do with the iOS8 SDK which means even if i run it against the is deployment, I could be affected by it. That's why I posted my code, so I could weed out the possibility of it being my code.

Now Im trying to use AFHTTPSessionManager instead since Ive read the issue will not present itself when using NSURLSession, but Im wondering if I can how to queue up these NSURLSessionDataTasks.
AFHTTPSessionManager has a GET method which returns an NSURLSessionDataTask. I read somewhere that these cannot be queued up like AFHTTPRequestOperations. (https://github.com/AFNetworking/AFNetworking/issues/1504). How could I manage a batch of operations then?

I did use this option and I get a different error. I get a code -1011 401 unauthorized request, which is probably due to my sending the authorization in a post, not a get. But it definitely proves the other error is 'probably' due to using AFHTTPRequestOperation.

Or would the recursive block suggestion work for me? (http://stackoverflow.com/questions/25372318/error-domain-nsurlerrordomain-code-1005-the-network-connection-was-lost). Or what other options are there?

Thanks

I found a temporary solution to the problem, which is to re-connect to the site ..

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

Example:

-(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;
     }

}

I hope that the solution be appropriate.

Thanks

I have the same problem on iOS8 with cellular (works fine on iOS7) when trying to access images on Azure cloud hosting. The workaround I used is to create an extra (sub)domain pointing to the same file
location. On connection failure I switch the NSURL of the request to the second 'failover' (sub)domain. Works fine so far.

Anyone already tried the 8.2 beta SDK?

Firing the POST request TWICE worked for me.
It is a really dirty solution but I think is the easiest one for now.
Example:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

NSDictionary *params = @{my parameters};

[manager POST:@"http://www.myserver.com/myfile.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

    //Success?

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    ///Try again in case of failure
    [manager POST:@"http://www.myserver.com/myfile.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

        //SUCCESS 99%

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[[UIAlertView alloc] initWithTitle:@"Something went wrong"
                                    message:@"Please retry. updateUserInfoToDB"
                                   delegate:self
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil] show];

    }];
}];

It looks like there is no way to set close for Connection in HTTP header with NSURLSession, iOS just ignores the value and always sends keep-alive

The only way i've found around this, is using a recurring block. On some occasions it can loop 200+ times before getting a good connection.

I am not experiencing such a problem anymore.

I have this problem too:

This problem started after changing the server I am trying to connect to from a normal EC2 instance to Elastic Load Balancer which points to the original EC2 instance.
The OS is iOS8.02.

Client side: "Connection: close" in HTTP header doesn't work (but I still apply it anyway).
My server is a AWS elastic load balancer so I have no ability to turn-off "keep-alive".
ELB has a "Idle timeout" configuration which I think refers to the time-limit on the "keep-alive" setting.

My current workaround is @ddaddy and @rambodrahmani approach:
Except that I only redo the request if (error.code == -1005) (where error is the NSError returned by AFNetworking).

Sometimes the request is redone more than 5 times as the -1005 error keeps occurring. I also have a button for the user to cancel the request to prevent an infinite loop of requests (but it isn't necessary because eventually a valid connection is made).

I found an even better approach is to redo the request after some period of time to maximise chance of connection naturally closing.
So as an extension to above code:

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

@rickblokdijk I tried 8.2 - still no luck - and I've been trying all the workarounds listed here and I can't get any of them to work - I keep getting error code: -1001 (its a request timeout) - but all my code worked fine in iOS 7 so I'm guessing I'm in the same boat as everyone here - any help would be greatly appreciated...I am just testing on my home network using my laptop as the server running the latest version of Apache and I am using a PHP backend. Thanks in advance.

I digged a bit into that issue here and also tested the project, provided by @Dimillian at https://github.com/AFNetworking/AFNetworking/issues/2314#issuecomment-56529701

After some testing and digging I found out, that the header for his and my test-server look different. His API returns the header Connection = "Keep-Alive"; \n "Keep-Alive" = "timeout=5, max=100"; whereby my API returns the following header Connection = "Keep-Alive" but my server does not send the Keep-Alive header.

I somewhere found a link to that website http://web.archive.org/web/20100813132504/http://www.io.com/~maus/HttpKeepAlive.html where they write, that the keep-alive is a quite undefined behavior in HTTP 1.0 ... I can't say what version I use, out of what I see in the debug-log, but I guess it's HTTP 1.1.

Reading on at http://en.wikipedia.org/wiki/HTTP_persistent_connection#HTTP_1.1 I read, that the default time for keeping the sessions on Apache is 5 seconds on Apache 2.2 and later. The earlier versions kept them for 15 seconds. I have not found any information on Nginx, that I use, aside of this website (sorry for just pasting it without first confirming it's value :)) http://nginx.com/blog/http-keepalives-and-web-performance/

Anyone knowing any default-settings on keep-alive? I only know that it's by default activated for HTTP 1.1 connections. I am specially interested in after how many seconds Nginx drops the session, to check how long I have to wait to get it failing :smile:

But if the reason is timing, why is working with firing the post request twice?

Sometimes mine fire 50-100 times before it works.

The key is to wait before firing it again. iOS think the connection is
still open so it sends it on the same and fail.
On Wed 4 Feb 2015 at 12:38 ddaddy [email protected] wrote:

Sometimes mine fire 50-100 times before it works.

—
Reply to this email directly or view it on GitHub
https://github.com/AFNetworking/AFNetworking/issues/2314#issuecomment-72840663
.

Yes I agree, although how long is the right amount of time to wait?
Firing it recursively makes it go through as soon as it's closed.

If someone else is searching for some timeout for Nginx:

http://serverfault.com/questions/583609/should-keepalive-timeout-be-removed-from-nginx-config

Nginx closes keepalive connections when the worker_connections limit is reached.

http://nginx.org/en/docs/http/ngx_http_core_module.html#keepalive_timeout

Syntax:     keepalive_timeout timeout [header_timeout];
Default:    keepalive_timeout 75s;
Context:    http, server, location

The first parameter sets a timeout during which a keep-alive client connection will stay open on the server side. The zero value disables keep-alive client connections. The optional second parameter sets a value in the “Keep-Alive: timeout=time” response header field. Two parameters may differ.

So, the solution, that @abournier provided here for nginx, should work - but it should neither be needed if I take a look at what @Dimillian wrote:

Edit: We also noticed that iOS expire the connection after around 30 seconds, so you also need to take that into account.

That said, another possible solution would to set your timeout above 30 seconds. As the default of nginx is up to 75 seconds, this shouldn't be a problem if you haven't changed that. The only case for you would then be if the worker_connections limit is reached :wink:

Or do I get something wrong here?

Thanks everybody for sharing ideas.
But is there any solution to fix it once and for all on client side? I mean wrap all the requests using AFHTTPRequestOperationManager and repeat it there in case of an error or something like that?

Thanks

We just increased our timeout to 75 in order to test, and it works.

@artemyarulin Yeah, client side If you don't have access to the server config I don't see an easy or clean fix. Repeating the request seems to be the only solution and it's quite dirty.

Bad news to those who try overriding Connection header value to "close" in your requests:

The NSURLConnection class and NSURLSession classes are designed to handle various aspects of the HTTP protocol for you. As a result, you should not modify the following headers:

Authorization

Connection

Host

WWW-Authenticate

Source: NSMutableURLRequest documentation.

@Dimillian your sample project does not work anymore. The server always returns 405 error.

I'm not using AFNetworking but came across this issue while searching the web for a Safari-SSL-POST related disconnection issue (under standard HTML circumstances) what seems to have a common cause. I want to share my findings with you in case it helps:

Error description: Safari on current iOS 8 (iPad and iPhone) and(!) current MacOSX disconnects showing a page-could-not-be-loaded error when combining:

  • a POST to a
  • HTTPS location

What we found out:

As @Dimillian pointed out: There seems to be a client-side Keepalive timeout at 30 seconds. Raising our webservers Keepalive to 30 seconds fixed the problem completely as far as I can see.

Before raising the timeout (default were 5 seconds) we could quite reliably provoke the problem when opening a html page containing a form with a post action in an https context (with a https target) when sending the form within the timeframe > 5 seconds and < 30 seconds.

So it's just a hypothesis but it looks like Safari (on both current iOS an current MacOS) erroneously relies on having an active keepalive connection when receiving a POST in https context.

To make it even more sophisticated: We could reproduce it on most (all 2.4 versions) but not all (some 2.2 versions) of our apache webservers. Deactivating keepalive did not fix the problem in our case.

We had no problem whatsoever in any other browser (Chrome, Firefox, IE) or somewhat older MacOS/Safari Versions.

If this hypothesis should be correct - this looks like quite a severe Apple bug to me...

@proligde Did you filed a radar? Yes, I also had the same error on OS X and iOS Safari. This is very serious, and Apple didn't even looked at my report... yet.

@Dimillian nope - to be honest: Not being an Apple developer I didn't know there is something like radar :-) I've just filed it there. Maybe one of us got some luck...

I've also run into this issue. For me, it times out exactly as described by this developer here http://stackoverflow.com/questions/28904723/how-to-solve-timeout-issues-caused-by-bad-http-persistent-connection

I can consistently reproduce it on both the simulator and the device (only on Wifi).

I am currently working around it by setting the keepalive to 30 seconds on the server as suggested by @proligde

Hopefully Apple will fix this. It seems like a major bug. I'm surprised it hasn't been addressed yet.

I use AFNetworking in my app. One of my tester said that sometimes he sees 'no connection' message, which means AFNetworking gives a certain error. When this problem happen, he said 'no connection' will keep appear until he re-install the app & works fine. I don't know exact network condition he used ( maybe bad network ), but this problem never happen to me

So it seems AFNetworking uses same connection like before ( which gives error ). Maybe it is related to this issue posted here.

I'm planning to add timestamp to all my POST requests. I think it will makes every request unique. What do you guys think about this? If each request unique, will AFNetworking/URLRequest establish new connection for each request? (even server send Keep-Alive )

No, even if each request is unique, the connection will be reused.
The clean solution is to increase the keep alive timeout on the server to
at least 30 seconds

On Wednesday, 22 April 2015, youngsiris [email protected] wrote:

I use AFNetworking in my app. One of my tester said that sometimes he sees
'no connection' message, which means AFNetworking gives a certain error.
When this problem happen, he said 'no connection' will keep appear until he
re-install the app & works fine. I don't know exact network condition he
used ( maybe bad network ), but this problem never happen to me

So it seems AFNetworking uses same connection like before ( which gives
error ). Maybe it is related to this issue posted here.

I'm planning to add timestamp to all my POST requests. I think it will
makes every request unique. What do you guys think about this? If each
request unique, will AFNetworking/URLRequest establish new connection for
each request? (even server send Keep-Alive )

—
Reply to this email directly or view it on GitHub
https://github.com/AFNetworking/AFNetworking/issues/2314#issuecomment-95034745
.

@arthurdarcet Thanks for the reply. One more question; what if server send 'Connection:Close' in response header? Will it affect the result?

@youngsiris I'm sure, I haven't tried, please respond to http://stackoverflow.com/a/25996971/2258249 if it works

I saw that AFNetworking had fix this problem from stackoverflow, so where can I find the commit of the issue.

Thanks to everyone who has taken the time to investigate and share their findings in this thread.

The best description of the problem and proposed solution I've come across is this Stack Overflow thread, as mentioned before in this thread.

Unfortunately, because this appears to be a bug in the underlying Foundation URL Loading System, there is no real way for AFNetworking to work around this issue. Unless anyone objects, I'm going to close this thread, as there is no actionable resolution on our part.

If anyone has any updates, please feel free to continue the discussion here. If anyone happens to find a workaround that AFNetworking can adopt, we'd be glad to take a look—please open a PR if you do.

Deleting the specific Wi-Fi connection and then reconnecting by supplying the password again solved my problem. See my stack overflow response for more details at the bottom of this page:

I completely solved this problem by deleting my Wi-Fi network connection and re-instantiating it by choosing it from the network connection list and providing the password again. See my stack overflow response here at the bottom of the page:

http://stackoverflow.com/questions/25797339/nsurlconnection-get-request-returns-1005-the-network-connection-was-lost

I'm having this issue too. On an iOS 8.4 device and also on an iphone 5s with 8.1. We have 2 iphone 5s with iOS but only one behaves like this.
I am on node.js with sails and have tried setting the timeout serverside higher than 30 seconds by doing this:
sails.hooks.http.server.on('connection', function(socket)
{
console.log("A new connection was made by a client.");
socket.setTimeout(35 * 1000);
// 30 second timeout. Change this as you see fit.
});
This didn't work.
Also I've tried to close the connection by setting connection : close and I receive the header back as "Connection":"close" so I guess I've set it correctly but I can't be sure(Used to be "keep-alive" so I think I've set it correctly). This doesn't work either.
Also I've read that I may be able to solve this by setting client side the header "keep-alive-info max" to 1. Does anyone know how to set that on iOS?
Did anyone manage to fix this with NodeJS and iOS8+? If so, how?

We have 3 iOS 8.4 two iPhones 4S and one iPhone 5
We have the same issue:
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."
Error Domain=com.amazonaws.iossdk.ClientErrorDomain Code=-1 "The operation couldn’t be completed. (com.amazonaws.iossdk.ClientErrorDomain error -1

Both issues related to timeout occurrences,
Anyone has a solution for this ?

@arthurdarcet thanks, eventually implemented retry on timeout procedure as well as caching, this taught me not to trust the connectivity and making the app more robust to such failures from every future module i choose to use.

http://stackoverflow.com/a/25996971/2258249
also the discussion above best answer is to "Restart the simulator" since im not working on a simulator then it is not relevant to me.

For mean time. This can solve the problem

[manager.requestSerializer setValue:@"close" forHTTPHeaderField:@"Connection"];

@arthurdarcet can you tell what tweaks you did on server side.

@arthurdarcet Thanks

nice shot

Hi, we recently spotted this case in our application when using [NSURLSession dataTaskWithRequest:completionHandler:]. What is strange, upon calling completionHandler we receive following set of parameters from iOS:

  • data is nil
  • response represents successful server response with statusCode 200
  • error is not nil and represents -1005 error.
    What is more, it looks like server returns correct response body as well (we investigated it using mitmproxy). However, for some reason, iOS interprets sth as "Connection was lost" error and ignores response body (thus, data is nil).

I would like to kindly ask you - is that sth you have experienced as well?

@manicaesar Seeing the EXACT same things you are describing -- have yet to understand the underlying cause

@manicaesar @kamranpirwani Any luck? I'm seeing the same issue.

I encountered this issue and none of the answers here or even from StackOverflow solve the issue. Setting the HTTPShouldSetCookies of NSURLSessionConfiguration fixed it.

@manicaesar @kamranpirwani @jhrasco Any chance any of you are connecting to an AWS-hosted app using AWS's Application Load Balancer (ALB)? I'm seeing it send unexpected HTTP2/GOAWAY packets when scaling the server-side cluster up or down. Reverted to Elastic Load Balancer (ELB) temporarily resolved the issue and we're talking with Amazon about the underlying issue.

Does anyone know if the keepalive issue is fixed on iOS 9 or 10, or is disabling it still necessary?

@hmoffatt — Still present in iOS 10. Thats what I was on when reproducing using AWS's ALB per my previous comment.

Has anyone tested with HTTP/2 to see if that improves things on the Safari side?

Just an update, this is still an issue on iOS 11.3.

Any update on this issue ?

Tested on iOS 12.0 & the issue hasn't been fixed yet.

Was this page helpful?
0 / 5 - 0 ratings