Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Flutter and app store releases

URLSession fails with error -1005, the network connection was lost

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

Short answer

Error -1005 means the TCP connection carrying your HTTP request dropped while the request was in progress. A few are normal on mobile networks. Many of them point at the server closing connections. Retry idempotent requests, give POST requests an operation ID before retrying, and trace the traffic if the errors are frequent on good Wi-Fi.

  • Applies to Xcode 26, Swift 6, iOS 26, URLSession
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Log the failing request's HTTP method and the error code together. The method decides which cause below applies, and it shows whether the failures cluster on one endpoint.

    // in your URLSession error handling
    if let urlError = error as? URLError, urlError.code == .networkConnectionLost {
        print("-1005 on \(request.httpMethod ?? "GET") \(request.url?.path ?? "")")
    }
  2. 2Match what you see, then jump to its fix

    1. 1-1005 appears on POST requests, and after a retry the server shows the operation twice (or you cannot tell whether it ran)A POST was cut off and you retry it blindlyFix
    2. 2-1005 comes often even on stable Wi-Fi, and always from the same host or endpointYour server closes connections unexpectedlyFix
    3. 3-1005 on GET, HEAD or PUT requests, only while moving between networks or with weak signalA real network drop during a safe requestFix

What does the error look like?

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

Cause 1 of 3

A POST was cut off and you retry it blindly

1Check

Apple explains that when the connection drops mid-request, the client cannot know whether the server saw the request. URLSession can retry a request on its own only if the HTTP method is idempotent. POST is not idempotent, so Apple says you need request-specific retry logic.

grep -rn "httpMethod" --include=*.swift .

2Fix

Send a unique ID with every operation. After a -1005, ask the server whether that ID already exists. Retry only if it does not. If an idempotent method such as GET or PUT is used for something that changes state, Apple says to change the method instead, since URLSession may retry it unsafely.

var request = URLRequest(url: url)
request.httpMethod = "POST"
let operationID = UUID().uuidString
request.setValue(operationID, forHTTPHeaderField: "Idempotency-Key")

3Verify

Cut the connection on purpose in a test (airplane mode during the call) and confirm the server processed the operation once.

# server side: count rows or log lines for one operation ID, expect 1

Confirmed by developer.apple.com

Did this fix it?

Cause 2 of 3

Your server closes connections unexpectedly

1Check

Apple's guidance is that a few -1005 errors are normal, but a large number in good network conditions suggests a problem between URLSession and the server, such as the server closing connections. Apple points to a packet trace and CFNetwork diagnostic logging to see what really happens on the wire. First see whether the server answers cleanly from a plain client.

curl -v https://api.example.com/health

2Fix

Find what closes the socket on the server or in front of it (a load balancer, proxy or app server with a short idle or request timeout) and make it keep the connection until the response is sent. Then confirm with a packet trace that the connection is no longer reset.

# no client-side change: fix the server or proxy timeout that ends the connection

3Verify

Repeat the failing request many times from the app and from curl and watch the -1005 count drop to the normal background level.

for i in $(seq 1 50); do curl -s -o /dev/null -w "%{http_code}\n" https://api.example.com/health; done | sort | uniq -c

Confirmed by developer.apple.com

Did this fix it?

Cause 3 of 3

A real network drop during a safe request

1Check

Apple documents that waitsForConnectivity only applies while a connection is being established. If a connection is up and then drops, the task fails with a connection-lost error. That setting will not remove this error.

grep -rn "waitsForConnectivity" --include=*.swift .

2Fix

For idempotent requests, retry once straight away, then back off with your app's normal retry policy. Do not retry non-idempotent methods this way.

func send(_ request: URLRequest, retried: Bool = false) async throws -> (Data, URLResponse) {
    do {
        return try await URLSession.shared.data(for: request)
    } catch let error as URLError
        where error.code == .networkConnectionLost && !retried
              && ["GET", "HEAD", "PUT", "DELETE"].contains(request.httpMethod ?? "GET") {
        return try await send(request, retried: true)
    }
}

3Verify

Switch Wi-Fi off during a GET and confirm the user sees a result or a clear error, not a hang.

# manual: start a large GET, toggle Wi-Fi, check the retry happens once

Confirmed by developer.apple.com

Did this fix it?

How do I stop it coming back?

  • Use the HTTP method that matches the action: GET for reads, POST for creating something that must not repeat.
  • Give every state-changing request an operation ID the server can look up.
  • Count -1005 per host in your logging so a rise stands out from the normal background level.
  • Keep server and proxy idle timeouts longer than your slowest response.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Mobile apps

InstanceID token() no longer works in a Swift Firebase app

Instance ID calls fail to compile after upgrading Firebase to 8.0.0 or later

Firebase removed the Instance ID dependency from Messaging in 8.0.0, so InstanceID.instanceID() calls no longer belong in a current app.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.