Technical Q&A QA1941

Handling “The network connection was lost” Errors

Q:  My app is seeing NSURLErrorNetworkConnectionLost errors returned by NSURLSession. How should I handle these 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.

It’s easy to understand why this restriction is important. Consider a POST request that triggers a bank transfer. If NSURLSession has started transmitting the request and then the connection fails, it can’t distinguish between the following cases:

Given the above, the correct way to handle NSURLErrorNetworkConnectionLost depends on the type of request:

For this to work you must make sure that you use the right HTTP method for each request. There are two ways this can go wrong:

Finally, as an app developer it’s reasonable to expect a small number of NSURLErrorNetworkConnectionLost errors caused by problems with the underlying network. However, if you’re seeing a large number of these errors, and especially if they are raised in environments with good network connectivity, there might be a problem with NSURLSession talking to your server. You can investigate that by looking at the on-the-wire traffic to see whether there’s an obvious underlying cause for these errors, for example, your server actually closing connections unexpectedly.

For information about how to look at the on-the-wire traffic, see Getting a Packet Trace. You can also use the techniques described in CFNetwork Diagnostic Logging to look at NSURLSession’s internal state.

Document Revision History


New document that describes how to handle the NSURLErrorNetworkConnectionLost error.