Skip to main content

Connecting

VPN Profile​

Before connecting, a VPN profile must be installed. This shows a system dialog asking the user to allow VPN configurations:

let vpn = KapeVPNManager(handle: handle)
try await vpn.installProfile()

vpn.isProfileInstalled // true after approval

The profile persists across app launches. You only need to install it once.

Connection Modes​

KapeVPNManager supports two connection modes via KapeConnectionMode:

// Automatic — SDK picks the best available server
try await vpn.connect(mode: .auto)

// Manual — connect to a specific server
try await vpn.connect(mode: .manual(locationId: "us-east-1"))

// Direct shorthand for manual
try await vpn.connect(to: "us-east-1")
ModeBehaviour
.autoStops running measurements, then connects to the first location of the stored Smart Location ranking for the current plan and network. With none, runs a fast search (.fast, about 1–2 s) and connects to its best location. See below for the fallback order.
.manual(locationId:)Connects to the specified location. The locationId comes from KapeServerLocation.id.
info

With the VPN disconnected and Smart Locations in the license, .auto first stops any ping, Smart Location or speed test run in progress, as every connect does (see Measurements are stopped first), so it never waits for one. It then picks in this order:

  1. The first location of the stored ranking.
  2. With none stored, the best location of a fast search.
  3. When no location answers, the location nearest the user.
  4. When the fast search fails, the same order as without measuring (below): the stored ranking, the last measured ranking returned in this process, then the location nearest the user's real location.

It never uses the first location of the catalog. When none of these is available, connect(mode: .auto) throws KapeVPNError.noLocationsAvailable. Cancelling the task that awaits it during the fast search throws CancellationError, and nothing connects.

While the VPN is connecting, connected, reconnecting, paused or disconnecting, or without Smart Locations in the license, .auto measures nothing and picks in this order: the stored ranking, the last measured ranking returned in this process, then the location nearest the user's real location. try await vpn.resolveAutoLocationId() shows where .auto would go without measuring, in that same order.

Falling back to other locations​

.auto and .manual stay on one location: if every server in it fails, the tunnel keeps retrying that location. That is a dead end for a user who can only change location once connected, such as a free-tier user whose Smart Location is unreachable. For them, pass an ordered list of locations to connect(toAnyOf:):

try await vpn.connect(toAnyOf: ["214", "26", "33"])

The tunnel tries the locations in order. It moves on from a location when:

  • every one of its servers has failed to connect,
  • it has no server for the selected protocol, or
  • its server list cannot be fetched while the device is online.

When the end of the list is reached, the tunnel starts over from the front, staying in .connecting (.reconnecting after a first connect) rather than ending the session — at once if it had servers to try, after a backoff if every location came back empty or unreachable. Only if no location has any server at all on the first attempt does the session end, with .noEndpointsAvailable.

What a reconnect (network change, tunnel drop) does once connected is set by the fallback parameter, a KapeLocationFallback:

  • .untilConnected (the default): the tunnel stays on the location it connected to. It tries that location's other servers, then fetches its servers again, and keeps retrying it. It never moves to another location of the list.
  • .always: the tunnel tries the connected location's other servers, then the other locations in list order, then starts over from the front.
try await vpn.connect(toAnyOf: ["214", "26", "33"], fallback: .always)

Either way, the fallback applies to each new connect(toAnyOf:): it starts again from the whole list.

Which location is connected​

selectedLocationId is the first location of the list. The location the tunnel actually connected to is connectedLocationId, which is set before connectionStatus turns .connected:

vpn.$connectedLocationId
.sink { locationId in
// nil when no session is up
}
.store(in: &cancellables)

connectedLocationId is set for every connection mode. It is kept while reconnecting and is nil once disconnected. While the tunnel switches to another location it keeps naming the old one until the switch has happened.

Which location is being tried​

connectingLocationId names the location the tunnel is trying right now, so a "Connecting to …" label can follow a connect(toAnyOf:) connect as it falls back. It changes while connectionStatus stays .connecting:

vpn.$connectingLocationId
.sink { locationId in
// nil unless connectionStatus is .connecting or .reconnecting
}
.store(in: &cancellables)

It is nil before the first attempt: for a moment at the start of a connect, and during a reconnect while the tunnel waits for the network or fetches servers. Fall back to connectedLocationId or a generic label then. Between attempts it keeps naming the last location tried, including while the tunnel backs off after the whole list failed. It is nil again once a location connects (connectedLocationId then names it). During a location switch it names the new location once the tunnel starts trying it.

What happens on connect​

All modes follow the same internal flow:

  1. Saves the selected location to shared state (App Group container)
  2. Stops a running ping, Smart Location or speed test, and waits until it has stopped (see below)
  3. Starts the Network Extension process
  4. The extension reads the location, the selected VPN protocol, and authenticates endpoints via the SDK
  5. Establishes the tunnel (WireGuard, Lightway, or OpenVPN, depending on the selected protocol)

To change the protocol, see VPN Protocol.

If already connected, calling any connect variant with a different location will switch servers without disconnecting first.

Measurements are stopped first​

A ping or measurement sent through the tunnel would time the VPN server, and the SDK would store the result as if it had been measured on the user's network. So every connect variant, a location switch included, first cancels a ping sweep, Smart Location measurement or speed test started through KapeLocationService or KapeSpeedTest, and starts the tunnel only once it has stopped:

  • A caller awaiting the measurement, or queued behind it, gets CancellationError.
  • A measurement started while the connect is stopping one gets CancellationError too, without measuring.
  • With nothing running, the connect does not wait.
  • With .auto, runs are stopped before the location is picked. The pick's own fast search is the only measurement allowed while it picks, and another connect stops it too. A measurement started after the pick is stopped before the tunnel starts, as above.

The SDK gives a measurement 5 s to stop. One that has not stopped by then is left to finish, and the tunnel starts. A tunnel started without your app, by Connect on Demand or from iOS Settings, stops nothing.

Disconnecting​

await vpn.disconnect()

Signing Out​

await vpn.signOut()

Goes further than disconnect(): it also removes the installed VPN configuration and resets every persisted VPN setting — selected location, Dedicated IP selection, active subscription, proxies (and their keychain secrets), Connect on Demand rules and pause state, plus protocol, transport, MTU, cipher, SNI, kill switch, split tunnel, custom DNS and Advanced Protection. The next account starts from SDK defaults.

Call it alongside KapeAuthClient.logout(), which cannot reach the tunnel itself — see Authentication. It is non-throwing, idempotent and safe to call with nothing connected.

Connection Status​

Observe the connection status via Combine:

vpn.$connectionStatus
.sink { status in
switch status {
case .disconnected: // Not connected
case .connecting: // Establishing tunnel
case .connected: // Tunnel active
case .reconnecting: // Tunnel lost, no network, or resuming a pause — recovering
case .paused: // Paused
case .disconnecting: // Tearing down
}
}
.store(in: &cancellables)

Connection Errors​

Tunnel start errors occur asynchronously inside the Network Extension process and are not propagated as thrown errors from connect(to:). Instead, KapeVPNManager exposes a dedicated Combine publisher:

vpn.$connectionError
.sink { error in
// nil once the tunnel connects or is stopped
print("Tunnel error: \(error?.localizedDescription ?? "none")")
}
.store(in: &cancellables)

connectionError is of type KapeVPNError?. It is set:

  • while the status is .connecting and the tunnel's latest attempt failed — the tunnel keeps retrying, and the error follows its latest failure;
  • when the connect fails and the status reaches .disconnected.

It is cleared once the tunnel connects or is stopped, and on the next connect(to:) or connect(mode:) call. It publishes only when it changes, so a retry that fails the same way is not reported again.

Why errors are not thrown from connect​

connect(to:) and connect(mode:) both call startVPNTunnel() on the NETunnelProviderSession. This call returns immediately — the tunnel runs in a separate, sandboxed process. Any error that occurs during WireGuard setup (no endpoints, authentication failure, handshake timeout) is thrown inside the extension and terminates the extension process; it never reaches the calling app.

KapePacketTunnelProvider writes the error description to a shared JSON file in the App Group container before rethrowing. When a connect ends in .disconnected (delivered via Darwin notification), KapeVPNManager reads that file to populate connectionError. A stop clears the file first, so a stop is never reported as an error.

Subscribing in SwiftUI​

vpn.$connectionError
.receive(on: DispatchQueue.main)
.map { $0?.localizedDescription }
.sink { [weak self] description in
self?.errorMessage = description
}
.store(in: &cancellables)

Common error values​

ScenarioKapeVPNError case
No endpoints available for the location.noEndpointsAvailable
WireGuard authentication with the server failed.authenticationFailed
WireGuard handshake timed out.tunnelStartFailed
Another VPN profile is active.tunnelStartFailed
info

connectionError is nil while the tunnel is connected. A value while .connecting means the tunnel is still retrying; show it as a reason, not as a final failure.