Fix: NSURLErrorDomain -1001, -1003, -1004 Errors in StoreKit Sandbox Purchases

Fix: NSURLErrorDomain -1001, -1003, -1004 Errors in StoreKit Sandbox Purchases
Quick answer: NSURLErrorDomain codes -1001 (timeout), -1003 (cannot find host), and -1004 (cannot connect to host) are CFNetwork-level network errors that surface during StoreKit Sandbox purchase attempts. They typically indicate transient Apple Sandbox infrastructure issues, not your code. Mitigate by retrying with exponential backoff, verifying device network stability, and testing on multiple networks.

Why this happens

These error codes originate from CFNetwork, not StoreKit itself. When you call SKPaymentQueue.default().add(payment), the framework establishes a secure connection to Apple’s purchase validation servers. In the Sandbox environment, this connection can fail due to:

  • Sandbox infrastructure instability: Apple’s test environment has lower uptime guarantees than production.
  • Network routing issues: Corporate Wi-Fi, VPNs, or carrier networks may block or mishandle connections to sandbox.itunes.apple.com.
  • Device-specific network state: A device switching between Wi-Fi and cellular (or VPN on/off) mid-request triggers -1001 (timeout) or -1004 (connection refused).

Product requests (SKProductsRequest) often succeed because they use a different, lighter-weight endpoint that is more resilient. The payment queue, however, requires a persistent, authenticated session to the transaction server, making it more sensitive to network fluctuations.

How to fix it

1. Implement retry logic with exponential backoff

Wrap the payment addition in a retry loop that respects the transient nature of these errors. Do not retry indefinitely—cap attempts and surface a user-friendly message after the last failure.

import StoreKit

final class PurchaseManager: NSObject {
    private let maxRetries = 3
    private var retryCount = 0

    func purchase(_ product: Product) async throws -> Transaction? {
        let payment = Payment(product: product)

        while true {
            do {
                try await SKPaymentQueue.default().add(payment)
                // Wait for transaction update via Transaction.updates
                for await update in Transaction.updates {
                    switch update {
                    case .verified(let transaction):
                        await transaction.finish()
                        return transaction
                    case .unverified(_, let error):
                        throw error
                    }
                }
            } catch let error as NSError where isTransientNetworkError(error) && retryCount < maxRetries {
                retryCount += 1
                let delay = pow(2.0, Double(retryCount)) // 2s, 4s, 8s
                try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
                continue
            } catch {
                throw error
            }
        }
    }

    private func isTransientNetworkError(_ error: NSError) -> Bool {
        guard error.domain == NSURLErrorDomain else { return false }
        return [-1001, -1003, -1004, -1005, -1009].contains(error.code)
    }
}

Key points:
– Check error.domain == NSURLErrorDomain and the specific codes.
– Use Task.sleep for async backoff; on older deployment targets, use DispatchQueue.global().asyncAfter.
– Always call transaction.finish() on verified transactions to avoid stuck purchases.

2. Validate network reachability before queuing

A quick pre-flight check avoids pointless retries when the device is clearly offline.

import Network

func isNetworkAvailable() async -> Bool {
    let monitor = NWPathMonitor()
    let queue = DispatchQueue(label: "NetworkMonitor")
    var isAvailable = false

    await withCheckedContinuation { continuation in
        monitor.pathUpdateHandler = { path in
            isAvailable = (path.status == .satisfied)
            monitor.cancel()
            continuation.resume()
        }
        monitor.start(queue: queue)
    }
    return isAvailable
}

Call this before add(payment). If it returns false, show an offline banner instead of hitting the queue.

3. Test on multiple network profiles

Since the issue is environment-dependent, verify behavior across:
– Home Wi-Fi (no VPN)
– Cellular (LTE/5G)
– Corporate Wi-Fi with proxy
– Personal hotspot

If the error only appears on one profile, the root cause is network policy (blocked ports, DNS filtering, captive portal), not your code.

4. Use a dedicated Sandbox Apple ID

Shared or stale Sandbox accounts can accumulate invalid receipt state. Create a fresh tester account in App Store Connect → Users and Access → Sandbox Testers for each test session. Sign out of the previous account in Settings → App Store → Sandbox Account before signing in with the new one.

5. File a Feedback Assistant report if persistent

When retries and network changes don’t help, the problem is likely on Apple’s Sandbox servers. Submit a Feedback Assistant report (formerly Radar) with:
– Device model, iOS version, Xcode version
– Exact error codes and timestamps
– Network type (Wi-Fi/cellular) and ISP
– Whether the same binary works on another device

Apple engineering uses these reports to correlate Sandbox outages.

How to prevent it

  • Always wrap add(payment) in a retry policy for the transient codes listed above.
  • Pre-check reachability with NWPathMonitor before initiating a purchase flow.
  • Rotate Sandbox tester accounts regularly; avoid reusing the same account across many test runs.
  • Test on real devices only—the Simulator uses a different network stack and masks these errors.
  • Log the full NSError (domain, code, userInfo) to your analytics so you can correlate spikes with Sandbox incidents.

FAQ

Why do product requests succeed while purchases fail?

SKProductsRequest hits a lightweight catalog endpoint that is highly cached and geographically distributed. The payment queue opens a mutually-authenticated TLS session to the transaction server, which has stricter timeout and routing requirements and runs on a separate, less redundant Sandbox fleet.

Are these errors ever caused by my code signing or provisioning profile?

No. Code signing issues produce SKError.Code.paymentInvalid or SKError.Code.paymentNotAllowed. The -1001/-1003/-1004 codes are pure CFNetwork transport failures; they appear after the app is already running and the payment object is valid.

Should I show these raw error codes to the user?

Never. Map them to friendly messages: “The App Store is temporarily unavailable. Please try again in a moment.” Retry silently first; only surface an alert after the final retry fails.

Quick reference: CFNetwork error codes

Code Constant Meaning
-1001 kCFURLErrorTimedOut Request exceeded timeout
-1003 kCFURLErrorCannotFindHost DNS resolution failed
-1004 kCFURLErrorCannotConnectToHost TCP/TLS handshake failed
-1005 kCFURLErrorNetworkConnectionLost Connection dropped mid-flight
-1009 kCFURLErrorNotConnectedToInternet No network interface active

All are defined in <CFNetwork/CFNetworkErrors.h> and bridged to NSURLErrorDomain.

Sources & credits

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