Fix: NSURLErrorDomain Code=-1005 in Swift and iOS Simulator

Fix: NSURLErrorDomain Code=-1005 in Swift and iOS Simulator

Written by

in

Quick answer: If NSURLErrorDomain Code=-1005 only happens in the iOS Simulator, fully quit and restart the Simulator (Cmd + Q or xcrun simctl shutdown all) to clear stuck virtual network sockets. If it happens on physical devices too, your server is closing idle HTTP Keep-Alive connections while URLSession tries to reuse them—increase the server’s Keep-Alive timeout past 30 seconds or add a single retry for URLError.networkConnectionLost in Swift.

Why this happens

When an HTTP request fails mid-flight on iOS or macOS, Apple’s networking stack logs an error that looks like this:

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
UserInfo={_kCFStreamErrorCodeKey=57, _kCFStreamErrorDomainKey=1,
NSLocalizedDescription=The network connection was lost.}

In Swift, this maps to URLError.networkConnectionLost. Unlike Code=-1009 (notConnectedToInternet), error -1005 means a TCP connection was established (or pulled from a connection pool) and then severed before a complete HTTP response arrived. You will usually see _kCFStreamErrorDomainKey=1 (POSIX error domain) paired with _kCFStreamErrorCodeKey=57 (ENOTCONN, socket not connected) or 54 (ECONNRESET, connection reset by peer).

Aside from genuinely flaky cellular reception, two repeatable bugs trigger Code=-1005 during development and production:

  1. Corrupted iOS Simulator sockets: After your Mac wakes from sleep, switches Wi-Fi networks, toggles a VPN, or disconnects from an HTTP debugging proxy, the Simulator’s networking bridge can hold onto dead sockets while macOS Safari continues working normally.
  2. HTTP Keep-Alive timeout mismatches: URLSession pools persistent HTTP connections so subsequent requests to the same host skip TCP and TLS handshakes. However, iOS often keeps idle connections in its pool for roughly 30 seconds—ignoring shorter timeout parameters sent in the server’s Keep-Alive header. If your server closes idle connections after 5 or 15 seconds, and your app sends a second request at second 16, URLSession writes to a socket the server has already closed.

How to fix it

1. Restart the iOS Simulator (if real devices work fine)

If NSURLErrorDomain Code=-1005 occurs on every request in the iOS Simulator—even against reliable APIs—test the exact same build on a physical iPhone or open the endpoint in macOS Safari. If the issue is isolated to the Simulator, its virtual network interface is stuck.

Closing the Simulator window alone is not always enough. Fully shut down the Simulator runtime:

  1. Bring Simulator to the foreground and press Cmd + Q to quit the app completely.
  2. Alternatively, shut down all active Simulator daemons from Terminal:
xcrun simctl shutdown all
  1. If you use a local MITM proxy such as Charles or Proxyman, quit or re-enable its macOS system proxy helper before pressing Cmd + R in Xcode again.

Relaunching the Simulator tears down stale virtual sockets and immediately resolves Simulator-only -1005 failures.

2. Increase the server’s HTTP Keep-Alive timeout

If the first request after launching your app succeeds, you wait several seconds, and the next request fails with Code=-1005, you are hitting an HTTP Keep-Alive race condition. Because URLSession aggressively reuses pooled HTTP/1.1 connections for around 30 seconds regardless of a shorter Keep-Alive: timeout=X header, servers with short idle timeouts drop the connection right as URLSession reuses it.

If you control the backend or reverse proxy, the cleanest fix is making sure the server keeps idle connections open longer than URLSession pools them:

  • Apache: Set KeepAliveTimeout above 30 seconds (for example, KeepAliveTimeout 60) in your Apache configuration. If raising the global timeout is not an option, you can disable keep-alive selectively for your app’s User-Agent using BrowserMatch with nokeepalive in setenvif.conf.
  • Nginx: Increase keepalive_timeout (for example, keepalive_timeout 65s;) in your http or server block.
  • Load balancers (AWS ALB, Cloudflare, etc.): Ensure the idle connection timeout on the load balancer is at least 60 seconds, and ensure your upstream application server (Node.js, Go, Gunicorn, Puma) has a keep-alive timeout slightly higher than the load balancer in front of it.
  • Enable HTTP/2: Switching your TLS endpoint to HTTP/2 largely eliminates HTTP/1.1 connection-pool races because requests multiplex over a single connection and servers signal shutdown explicitly with GOAWAY frames.

3. Retry transient Code -1005 errors safely in Swift

When you do not control the server—or when users move between Wi-Fi and cellular networks—your client code should handle URLError.networkConnectionLost gracefully.

A common misconception is setting Connection: close on URLRequest to disable connection reuse. Apple’s URLSession documentation explicitly reserves the Connection header; URLSession can ignore or overwrite it before sending the request over the wire.

Instead, wrap URLSession in a small helper that retries once when error.code == .networkConnectionLost. Be careful with HTTP methods: retrying GET, HEAD, PUT, and DELETE is safe because they are idempotent, whereas POST should only be retried automatically if your API accepts an Idempotency-Key header (since the server may have received the payload right before the response stream dropped).

import Foundation

enum ResilientNetworkClient {
    private static let idempotentMethods: Set<String> = [
        "GET", "HEAD", "PUT", "DELETE", "OPTIONS"
    ]

    static func data(
        for request: URLRequest,
        session: URLSession = .shared,
        maxRetries: Int = 1
    ) async throws -> (Data, URLResponse) {
        var attempt = 0

        while true {
            do {
                return try await session.data(for: request)
            } catch let error as URLError where error.code == .networkConnectionLost {
                let method = (request.httpMethod ?? "GET").uppercased()
                let hasIdempotencyKey = request.value(forHTTPHeaderField: "Idempotency-Key") != nil
                let isSafeToRetry = idempotentMethods.contains(method) || hasIdempotencyKey

                guard isSafeToRetry, attempt < maxRetries else {
                    throw error
                }

                attempt += 1
            }
        }
    }
}

When a stale pooled socket triggers -1005, URLSession evicts that dead connection from its pool. The immediate retry opens a fresh TCP connection and succeeds without noticeable delay.

4. Use a one-off ephemeral URLSession for stubborn legacy servers

If you have a non-idempotent POST endpoint on a third-party HTTP/1.1 server that drops idle connections aggressively and does not support idempotency keys, retrying blindly risks duplicate writes. In that narrow case, you can bypass stale pooled sockets by running the request on a dedicated ephemeral URLSession and invalidating it afterward:

import Foundation

func performIsolatedRequest(_ request: URLRequest) async throws -> (Data, URLResponse) {
    let configuration = URLSessionConfiguration.ephemeral
    configuration.requestCachePolicy = .reloadIgnoringLocalCacheData

    let session = URLSession(configuration: configuration)
    defer { session.finishTasksAndInvalidate() }

    return try await session.data(for: request)
}

Because the session starts with an empty connection pool and tears down its sockets via finishTasksAndInvalidate(), it never attempts to reuse an older half-closed TCP stream. Reserve this pattern for problematic endpoints only—creating a new URLSession per request forces a full TCP and TLS handshake every time.

How to prevent it

  • Enable HTTP/2 or HTTP/3 on your API servers so URLSession uses multiplexed connections with explicit teardown signaling instead of guessing HTTP/1.1 Keep-Alive lifetimes.
  • Keep backend idle timeouts above 60 seconds across both your reverse proxy and upstream app server (for example, Node.js defaults keepAliveTimeout to 5 seconds unless configured higher).
  • Attach Idempotency-Key headers to mutating POST requests so your app can safely retry URLError.networkConnectionLost on spotty mobile networks without double-charging or duplicating records.
  • Restart the Simulator after changing VPN or proxy states on macOS rather than debugging phantom socket errors in app code.

FAQ

Why does setting the “Connection: close” header not fix Code -1005 in URLSession?

Apple reserves several HTTP headers—including Connection, Content-Length, and Host—for internal management by URLSession. Even if you call request.setValue("close", forHTTPHeaderField: "Connection"), URLSession manages socket pooling itself and commonly strips or overrides that header before transmitting the request.

What does _kCFStreamErrorCodeKey=57 mean in an NSURLErrorDomain -1005 log?

When _kCFStreamErrorDomainKey equals 1, the error code comes from the POSIX errno.h table on Darwin. Code 57 is ENOTCONN (“Socket is not connected”) and code 54 is ECONNRESET (“Connection reset by peer”), both indicating the underlying TCP socket closed before the HTTP exchange finished.

Does Alamofire or AFNetworking have the same Code -1005 problem as URLSession?

Yes, because both Alamofire and AFNetworking are built directly on top of Apple’s URLSession networking stack. In Alamofire, you can handle stale keep-alive drops cleanly by attaching its built-in ConnectionLostRetryPolicy (or a custom RequestInterceptor) to your Session.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.