7

I'm converting my app to use HTTPS and would like to avoid the handshake cost as much as possible by keeping open a long-lived connection.

From reading the web and other answers on stack overflow it appears NSURLConnection should transparently keep the underlying socket open if the server responds with Connection: keep-alive and Keep-Alive: timeout=N.

However I am seeing that my connections are only kept open for around 10 seconds. My Keep-Alive response is set to much more than this. I am also sending Connection: keep-alive in my request headers.

Can anyone shed some light on this? I really don't want to have to use CFNetwork to achieve this.

ileitch
  • 532
  • 4
  • 12

2 Answers2

2

You have two ways:

As Tyler states in his answer here:

You can specify a timeout in your NSURLRequest object. One way to do this is to construct it via the requestWithURL:cachePolicy:timeoutInterval: method. (You can pass in the default NSURLRequestUseProtocolCachePolicy cachePolicy parameter if you don't want to worry about that part.) The timeout is a floating-point value in seconds, as are basically all time intervals in the iPhone SDK.

Also make sure your NSURLConnection's delegate is set and responds to the connection:didFailWithError: method. A connection always calls either this method or connectionDidFinishLoading: upon connection completion.

Or do what Kris suggests in his answer here:

ASIHTTPRequest has an expirePersistentConnections method. It may do what you're looking for.

It's not a drop-in replacement for NSURLConnection, but it's not too hard to port code from NSURLConnection to ASIHTTPRequest.

Community
  • 1
  • 1
Mina Nabil
  • 676
  • 6
  • 19
  • 2
    Please do not copy the words of others without proper attribution. I've edited the above to do so, but please make sure you do this in the future. – Brad Larson Jul 12 '12 at 18:42
0

The 10s problem got fixed in iOS7. I was having same problem and was following the bug. It got fixed in iOS 6 point some version.

8suhas
  • 1,460
  • 11
  • 20
  • 1
    iOS 9.2.1: It's not fixed. http://stackoverflow.com/questions/25372318/error-domain-nsurlerrordomain-code-1005-the-network-connection-was-lost/25996971#25996971 – jcady Mar 02 '16 at 22:47