URLSession fails with error -1005, the network connection was lost
Error 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.
Fix it fast
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 ?? "")") }2Match what you see, then jump to its fix
- 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
-1005 comes often even on stable Wi-Fi, and always from the same host or endpointYour server closes connections unexpectedlyFix - 3
-1005 on GET, HEAD or PUT requests, only while moving between networks or with weak signalA real network drop during a safe requestFix
- 1
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 1Confirmed by developer.apple.com
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/health2Fix
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 connection3Verify
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 -cConfirmed by developer.apple.com
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 onceConfirmed by developer.apple.com
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
UserDefaults logs 'Failed to read values in CFPrefsPlistSource' for an app group
Settings saved by the app are not visible to its extension, widget or sibling app that share the group
This log comes from the preferences system when UserDefaults is opened for an app group's suite.
3 causes, each with a fixMobile apps
iOS app crashes: Google Maps SDK must be initialized via provideAPIKey
Google Maps SDK for iOS must be initialized via [GMSServices provideAPIKey:...] prior to use
The Maps SDK throws this when a Maps object is created before GMSServices.provideAPIKey has run.
3 causes, each with a fixMobile apps
UIKit app crashes because it cannot find the storyboard
Could not find a storyboard named 'Main' in bundle NSBundle
UIStoryboard throws this exception when no storyboard file with that name exists in the bundle it searches.
3 causes, each with a fixMobile apps
Firebase on iOS asks for the FCM token before APNs has given one
Be sure to re-retrieve the FCM token once the APNS device token is set.
The Firebase Messaging SDK needs the APNs device token from iOS before it hands out an FCM token.
3 causes, each with a fixMobile apps
A test push from the Firebase console never shows up on the iPhone
didReceiveRegistrationToken prints a token, yet no notification arrives
When a console message is accepted but the iPhone stays silent, the break is between Firebase and APNs or inside the app.
4 causes, each with a fixMobile 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