DEV Community

Cover image for Your iOS App Says “Offline”—But Is It? Debugging API Failures With a VPN Enabled
KlarVPN
KlarVPN

Posted on AI-assisted

Your iOS App Says “Offline”—But Is It? Debugging API Failures With a VPN Enabled

A user connects their iPhone to a VPN, opens your app and sees:

No internet connection. Please try again.

They switch to another app, which works.

Your app may have encountered a real failure. But “no internet” might be the wrong diagnosis.

A hostname lookup can fail. A secure connection can fail. An API can return an authentication error. The response can arrive successfully and then fail JSON decoding.

A failed API operation does not automatically mean the device is offline—or that the VPN caused the failure.

The first useful fix is to preserve those distinctions in your networking code.

Start with what actually failed

Think of an API operation as several stages:

  1. Establish a usable network connection.
  2. Resolve the destination hostname when needed.
  3. Establish the secure connection.
  4. Exchange the HTTP request and response.
  5. Interpret the response body.

This is a debugging model, not a claim that every request creates a new connection or performs a fresh DNS lookup. Connections and lookup results can be reused.

The point is that failures at different stages need different handling.

Observation What to investigate
notConnectedToInternet Connectivity available to this request and applicable network restrictions
cannotFindHost Hostname spelling, DNS configuration and resolution
cannotConnectToHost Connection establishment, destination availability and routing
secureConnectionFailed TLS negotiation and trust-related diagnostics
An HTTP response outside the expected range API behavior, authentication, policy or server errors
A decoding error after an accepted response Response format and the app’s data model

An error category narrows the investigation. It rarely identifies the root cause by itself.

Keep HTTP failures separate from transport failures

One common mistake is assuming that URLSession throws whenever the server returns an error status.

A completed HTTP exchange can return a 401, 403 or 503 without producing a transport error. Your application needs to inspect the response status.

Here is a small Swift example for iOS 15 and later:

import Foundation

enum APIError: Error {
    case nonHTTPResponse
    case httpStatus(Int)
}

func fetchJSON<Value: Decodable>(
    _ type: Value.Type,
    request: URLRequest,
    session: URLSession
) async throws -> Value {
    let (data, response) = try await session.data(for: request)

    guard let httpResponse = response as? HTTPURLResponse else {
        throw APIError.nonHTTPResponse
    }

    guard (200..<300).contains(httpResponse.statusCode) else {
        throw APIError.httpStatus(httpResponse.statusCode)
    }

    return try JSONDecoder().decode(type, from: data)
}
Enter fullscreen mode Exit fullscreen mode

This keeps three useful outcomes distinct:

  • URLSession throws a transport-related error.
  • The application rejects an HTTP status.
  • The decoder rejects the response body.

The function assumes that an accepted response contains JSON matching Value. Adapt it for endpoints that legitimately return an empty body, such as a 204 response.

A production client may also decode structured API errors. Avoid discarding those details if they explain what the user needs to do.

Map errors to messages without inventing a cause

You can turn those categories into clearer interface messages:

func message(for error: Error) -> String? {
    if error is CancellationError {
        return nil
    }

    if let urlError = error as? URLError {
        switch urlError.code {
        case .cancelled:
            return nil

        case .notConnectedToInternet:
            return "A network connection is unavailable for this request."

        case .cannotFindHost, .dnsLookupFailed:
            return "The service address could not be resolved."

        case .cannotConnectToHost:
            return "The app could not connect to the service."

        case .secureConnectionFailed,
             .serverCertificateHasBadDate,
             .serverCertificateUntrusted,
             .serverCertificateHasUnknownRoot,
             .serverCertificateNotYetValid:
            return "A secure connection to the service could not be established."

        case .timedOut:
            return "The request took too long. Please try again."

        case .networkConnectionLost:
            return "The connection was interrupted."

        default:
            return "The request could not be completed."
        }
    }

    if let apiError = error as? APIError {
        switch apiError {
        case .httpStatus(401):
            return "Your session could not be verified. Please sign in again."

        case .httpStatus(403):
            return "The service did not allow this request."

        case .httpStatus(429):
            return "Too many requests. Please wait before trying again."

        case .httpStatus(let status) where (500..<600).contains(status):
            return "The service could not complete the request."

        default:
            return "The service returned an unexpected response."
        }
    }

    if error is DecodingError {
        return "The app could not read the service response."
    }

    return "Something went wrong. Please try again."
}
Enter fullscreen mode Exit fullscreen mode

Treat this as a starting point for your app’s language and API contract.

For example, a 401 may trigger a supported token-refresh flow before a sign-in prompt. A 403 should not automatically become “Your VPN is blocked.”

Apple also notes that hostname lookup failures should generally be handled through cannotFindHost; do not depend on receiving dnsLookupFailed.

Keep the original error for diagnostics. A friendly message should not replace the evidence needed to investigate it.

Use network monitoring as context

NWPathMonitor can help your app observe changes in the available network path.

It cannot tell you whether your API will authenticate the user, whether the server will return valid JSON or whether a particular request will finish successfully.

Apple describes a satisfied path as available for establishing connections and sending data. That is useful context, not an end-to-end API health check.

Avoid reducing your app’s state to a single Boolean named isOnline and treating it as a guarantee.

Instead, keep separate observations:

  • The network path appears available.
  • The latest request succeeded or failed.
  • The service returned a particular HTTP status.
  • The response could or could not be decoded.

Your interface can then say “Couldn’t refresh your account” while continuing to show previously loaded data, rather than incorrectly declaring the entire phone offline.

Compare VPN conditions without guessing

Use a physical device, a test account and a harmless endpoint you control. Record the iOS version, app build, network type and VPN configuration.

When including a VPN for iPhone in the test setup, document the conditions under which each request runs. The connected indicator alone does not explain an API failure.

A useful comparison includes:

Test condition Record
Stable connection without the VPN Baseline response or error
Same network with the VPN connected Whether the outcome changes
Request during a VPN reconnect Error category and timing
Wi-Fi-to-cellular transition Whether the request completes or fails
Deliberately returned test HTTP error Whether the interface shows the correct message
Deliberately malformed test JSON Whether decoding failure stays distinct from connectivity

Use the same endpoint and request parameters where possible. Repeat observations before attributing a difference to the VPN.

For a network comparison, use a non-cached test response so that locally stored data does not look like a successful live request.

A result that occurs only with the VPN enabled is a lead. It is not yet a diagnosis. Resolver behavior, routing, destination-side policies and timing may need separate investigation.

Log enough to connect the client and server evidence

Useful diagnostic fields include:

  • Timestamp and elapsed duration.
  • App and operating-system versions.
  • A safe operation name, such as loadProfile.
  • Error domain and numeric code.
  • HTTP status, when available.
  • A server-issued request identifier, when available.
  • Whether a network transition occurred near the failure.

Avoid logging authorization headers, session cookies, full response bodies or URLs containing sensitive query parameters.

Then compare client observations with the relevant server or gateway logs.

If the application server received nothing, investigate earlier stages—but remember that incomplete logging can also hide a request. If a gateway returned an error, inspect that layer before changing the app’s connectivity handling.

Do not fix a misleading message by weakening security

A TLS error deserves investigation.

Check the hostname, certificate chain, device time and relevant network configuration. Do not turn off certificate validation just to make the request succeed.

Similarly, automatically asking every affected user to disconnect their VPN can hide the actual defect. A controlled comparison can help debugging; it should not substitute for understanding the failure.

Make one failure easy to explain

Start with the code path that currently turns every error into “No internet.”

Preserve the underlying error, inspect HTTP status explicitly and keep decoding failures separate. Then test those paths deliberately.

The goal is a message you can defend:

The connection was interrupted.

The service rejected the request.

The app could not read the response.

Each tells the user something useful—and gives the developer a better place to start.

Top comments (0)