Skip to main content

Server Locations

Fetching Locations​

Fetch the list of available VPN servers after authentication:

import KapeVPN

let locations = KapeLocationService(handle: handle)
try await locations.fetchLocations()
info

KapeLocationService ships in the KapeVPNDiscovery module, which depends on KapeCore alone. KapeVPN re-exports it, so the import above is unchanged. If your target needs locations but not the tunnel, depend on KapeVPNDiscovery directly and construct the service with KapeLocationService(handle:selectedProtocolProvider:) — see OpenVPN Endpoint Configuration.

Locations are available as a flat list or grouped by continent:

// All locations
locations.allLocations // [KapeServerLocation]

// Grouped by continent
locations.locationsByContinent // [String: [KapeServerLocation]]
// e.g. ["Europe": [...], "North America": [...]]

Each KapeServerLocation provides:

PropertyTypeDescription
idStringLocation ID (pass to connect(to:))
nameStringHuman-readable name (e.g. "Frankfurt")
countryStringISO 3166-1 alpha-2 country code
continentStringContinent or region name
latitudeDoubleLatitude coordinate
longitudeDoubleLongitude coordinate
ratingKapeLocationRating?Quality rating (smart locations only)
pingMsUInt32?Latest measured ping, in milliseconds (set on Smart Location results and by pingLocations)

KapeLocationRating values: excellent, good, ok, degraded, poor, unknown. The enum is Comparable — higher ratings sort greater.

fetchLocations() uses the protocol currently stored in shared state. To ask for a specific protocol — "which locations serve OpenVPN?" — use KapeVPNDiscoveryService.fetchLocations(for:), which takes the protocol as an argument and reads no shared state. See OpenVPN Endpoint Configuration.

User Location​

fetchUserLocation() returns the user's real network identity: their public IP, country, region, ISP and coordinates. fetchVPNLocation() returns the VPN exit's identity, or nil when no tunnel is up.

let real = try await locations.fetchUserLocation() // KapeUserLocation
let vpn = try await locations.fetchVPNLocation() // KapeUserLocation?

The real location can be up to 24 hours old. Once the cached one has expired (after about 10 minutes), the SDK looks it up again, waits up to a second for the answer and otherwise returns the expired one; a later call returns the new one. When lookups keep failing it returns the last known real location, however old. fetchUserLocation() throws for a failed lookup only when no real location was ever seen.

Smart Locations​

Smart locations are the SDK's recommended servers for the current user. The rating combines several signals: ping latency (min, avg, median, p90), a short HTTP download measurement, and geographic distance. One ranking is stored per network — when the user reconnects to a known WiFi network, the stored ranking is returned immediately without re-running the measurement.

Stored rankings are also tied to the active subscription's plan. After an upgrade, a downgrade or a Dedicated IP claim, hasSmartLocations() returns false and the next getSmartLocations() measures afresh rather than ranking the previous plan's locations.

KapeLocationService exposes these methods — pick the one that matches what you need:

MethodWhat it doesProgress
getSmartLocations(search:)The stored ranking, else a measurement and ranking.none
updateSmartLocations(search:)Always measures, and replaces the stored ranking. For a user's request only.none
updateSmartLocationsThenPing(search:...)updateSmartLocations, then a full ping sweep that refreshes pingMs on the ranked result.both phases
pingLocations(onProgress:)Pure ping sweep — no ranking, no speed test.per location
fetchCachedSmartLocations()The stored ranking, or []. Never measures.none

getSmartLocations and updateSmartLocations are the Low Level SDK's calls of the same names.

Identical requests (e.g. two pingLocations()) made concurrently against the same KapeLocationService instance are coordinated automatically, only one test will run and the result will be share between the requests. If a second request is submitted after the first one has ended, the test is started from beginning to fetch new results. Different requests (e.g. one getSmartLocations() and one pingLocations(), or a getSmartLocations() and an updateSmartLocations()) made concurrently are serialized: only after the first test is done that the second test will start.

A speed test shares the SDK's single slot with these operations. Starting one cancels a ping or Smart Location operation in progress, which then throws CancellationError.

Reading and refreshing the ranking​

Read Smart Locations after fetchLocations():

try await locations.getSmartLocations()
locations.smartLocations // [KapeServerLocation] — sorted by best rating, each with `pingMs`
locations.smartLocationPings // [String: UInt32] — ping of every measured location, by location id

getSmartLocations() returns the ranking stored for the current plan and network, and measures only when there is none. Use it on launch, after a disconnect and after a network change.

Call updateSmartLocations() only when the user asks for fresh results. It always measures and replaces the stored ranking:

// Pull-to-refresh on the location list
try await locations.updateSmartLocations()

Offer a pull-to-refresh wherever you show Smart Locations. In rare cases (a slow location lookup right after a network switch, a move while connected) a ranking is measured or read under a location that is not the device's, and only updateSmartLocations() measures it again.

The measurement covers many more locations than it ranks. smartLocationPings holds the ping of every one of them, so a location list can show a ping on rows that did not make the ranking.

To read the stored ranking without measuring — for example on launch, before a scan has run:

let cached = try await locations.fetchCachedSmartLocations() // [] when nothing is stored

It returns the ranking stored for the current plan and network, with pingMs, never starts a measurement and publishes nothing. It reads a ranking only when hasSmartLocations() finds one for exactly this network, so it can return [] where getSmartLocations() returns one stored for a closely matching network, such as another access point of the same Wi-Fi network.

getSmartLocations, updateSmartLocations and updateSmartLocationsThenPing take a search for the measurement they run:

searchWhat it runsUse it
.full (default)The Low Level SDK's recommended search: it looks for five locations that answer well and runs a short HTTP download test on each, no upload. Up to about 30 s.Wherever the result feeds a list the user picks from
.fullWithoutThroughputThe full search without the HTTP download test: the ranking rests on ping alone.On cellular, to save data
.fastStops once one location has answered well, and runs no HTTP test: 1–2 s, and the ranking can hold fewer locations.When you need a good location quickly — "connect me now"
try await locations.getSmartLocations(search: .fullWithoutThroughput) // on cellular
try await locations.getSmartLocations(search: .fast) // "connect me now"

connect(mode: .auto) runs the fast search itself, so call it directly to connect.

One ranking is stored per network, whichever search made it. getSmartLocations() returns a stored ranking whatever search says, and so do fetchCachedSmartLocations() and connect(mode: .auto): after a fast search has stored one, they return it until the next updateSmartLocations(). So use .full wherever the result feeds a list the user picks from.

When a measurement fails​

A failed measurement never changes the stored ranking, and both calls return that ranking. With none stored, they return the locations nearest the user instead, closest first. They are rated .unknown, have no pingMs and are not stored, so the next call measures again. Show them like any other result. getSmartLocations() and updateSmartLocations() throw KapeVPNError.sdkError, and smartLocations keeps its previous value, only when the user's position is unknown too. updateSmartLocationsThenPing(...) falls back the same way, and its ping phase then fills in pingMs where a location answers; it throws before its ping phase starts.

Ping only​

For a pure latency sweep with no ranking or speed test, with per-location progress as each one completes:

try await locations.pingLocations { progress in
Task { @MainActor in
print("\(progress.locationId): \(progress.pingMs ?? 0) ms")
}
}

Fresh ranking, then ping progress​

For a user's request for fresh results that shows progress: updateSmartLocationsThenPing measures and stores a new ranking, reports it as soon as it is available, then reports per-location progress as latency is refreshed against the full location list:

try await locations.updateSmartLocationsThenPing(
onSmartLocationsUpdate: { ranked in
Task { @MainActor in print("ranked: \(ranked.count) locations") }
},
onPingProgress: { progress in
Task { @MainActor in print("\(progress.locationId): \(progress.pingMs ?? 0) ms") }
}
)
locations.smartLocations // final result: ranking with pingMs refreshed

There is no variant that returns the stored ranking first. For that, call getSmartLocations() and then pingLocations(onProgress:).

info

Call fetchLocations() before any of the methods above — smart/ping locations are resolved by matching against the full location list.

While connected or signed out​

A measurement taken through the tunnel would time the VPN server, not the user's network. So while the VPN is connecting, connected, reconnecting, paused or disconnecting, none of these methods starts one:

MethodWhile the VPN is up or coming up
getSmartLocations(search:), updateSmartLocations(search:)Return and publish the stored ranking. With none stored, the locations nearest the user's last real location: closest first, at most ten, rated .unknown, without pingMs. [] only when no real location is known.
updateSmartLocationsThenPing(...)The same, passed to onSmartLocationsUpdate. The ping phase is skipped.
pingLocations(onProgress:)Throws KapeVPNError.notAllowedWhileConnected.

The nearest locations are ordered by distance alone, so nothing is measured, with .detailed and .legacy network change reporting alike. The last real location is the one fetchUserLocation() returns. They are not stored, and fetchCachedSmartLocations() still returns [] while nothing is stored.

KapeLocationService(handle:) reads the status of the SDK's own VPN profile, so it does not see another app's VPN. The SDK recognises one only when the VPN exits on a Kape server, and only when it looks the device's location up again rather than reading the cached one. Then a ping sweep throws the same notAllowedWhileConnected, and a Smart Location call returns the stored ranking, else the nearest locations, rated .unknown and without pingMs. It throws KapeVPNError.sdkError when the SDK has never seen a real location. A VPN on another provider's servers is not recognised, and a measurement runs through it. A KapeVPNDiscovery-only consumer with a tunnel of its own reports it through the tunnelActivityProvider parameter of KapeLocationService(handle:selectedProtocolProvider:realLocationRelay:tunnelActivityProvider:).

While the user is signed out, all four methods throw KapeVPNError.notAuthenticated without measuring. Signing out stops a measurement in progress, which then throws CancellationError.

Connecting stops one too. Every KapeVPNManager connect cancels a running measurement and waits for it to stop before it starts the tunnel. Each caller awaiting it, or queued behind it, gets CancellationError, and so does a call made while the connect is stopping it. See Measurements are stopped first.

Network Monitoring​

The SDK tells the Low Level SDK which network the device is on and whether the VPN is up, so Smart Location results are measured and cached per network, and the device's real location stays cached across a VPN connect. This starts when KapeSdkHandle is created and needs no setup.

The SDK calls the Low Level SDK's networkChanged(change:) with:

ChangeWhenEffect
.switched(networkName:networkId:), with the SSID and BSSID of the network the traffic usesEvery network change: the network the app starts on, Wi-Fi ↔ cellular, joining a different Wi-Fi, and a network coming back after none (see below)Expires the cached location, the real location included: the next lookup waits up to a second for a new one
.vpnConnected / .vpnDisconnectedThe VPN reaching connected or disconnected, also after a location switch, and the VPN's state when KapeVPNManager is created. A pause is reported as .vpnDisconnected, once the traffic has left the tunnelKeeps the real location, so the next connect needs no location lookup first

The SSID and BSSID are empty strings while the traffic does not go over Wi-Fi, or when the SDK cannot read them; see Wi-Fi identity prerequisites.

The Low Level SDK stores the VPN state it is told, so it outlives the app: an app closed while connected leaves "VPN up" behind. That is why a VPN that is already disconnected when KapeVPNManager is created is reported too. .vpnDisconnected is not repeated while the Low Level SDK knows the VPN is down.

Path updates that change neither the connection type, the gateway nor the Wi-Fi network (link quality, DNS details) are ignored, and so are moments without a usable network: the next usable path is compared instead. When the device had no network at all and gets one back while the traffic goes outside a tunnel (the VPN off or paused), and nothing tells the new network from the one before, that is reported as a network change too: on cellular, or on Wi-Fi without the Wi-Fi identity prerequisites, it may be another carrier, or another Wi-Fi network with the same router address. Moments without a network in the 5 s after a VPN status change (connecting, connected, disconnecting, pausing, and so on) are the tunnel's and do not count, unless they last longer than 5 s.

The VPN tunnel coming up or going down changes the network path too, but not the network: the path has no usable network for a moment, then goes through the tunnel. Those path updates are not reported as a network change: the VPN state change above covers them. A real network change during a VPN session is still reported as one. While the VPN is up the OS reports no gateway, so without the Wi-Fi identity prerequisites, joining another Wi-Fi network during a session is reported when the VPN disconnects — but only if the app saw that session start, and no other network change was reported during it.

The SSID and BSSID follow the network path, not the Wi-Fi radio. The OS reports them a few seconds before the traffic moves: when Wi-Fi is turned off they are gone while the traffic still goes over Wi-Fi, and when Wi-Fi is joined they are there while the traffic still goes over cellular. So the SDK reports none while the traffic does not go over Wi-Fi, and keeps the previous ones while the traffic stays on the same Wi-Fi network. A Wi-Fi ↔ cellular switch then makes one call, carrying the new connection type and the new Wi-Fi network together, with or without the VPN connected. A Wi-Fi network whose captive portal has not been passed is not reported: the traffic still goes over cellular, so Smart Location results measured then are stored for cellular, not for that Wi-Fi network.

The Low Level SDK skips a .switched for the same network within 5 s of the previous one, and without the Wi-Fi identity every network looks the same. So a network change within 5 s of the last one is sent once the 5 s have passed, reading the SSID and BSSID again then. With .detailed reporting (see below), a VPN state change is sent at once, and when both are pending together, .switched goes first. Smart Location and ping measurements wait for pending calls, so they always run against the current network.

Network change reporting​

KapeSdkHandle.networkChangeReporting selects how these changes are reported. Set it at any time after creating the handle, for example from a feature flag. It is not persisted.

ValueReports
.detailed (default)As described above: .switched for a network change, .vpnConnected / .vpnDisconnected for the VPN
.legacyEvery change as one .switched with the SSID and BSSID, a VPN connect, disconnect or pause included. A disconnect or pause is then also reported as .vpnDisconnected, unless the Low Level SDK knows the VPN is down. A VPN state change waits out the 5 s window like a network change. Every connect after a VPN state change looks the location up again. The Low Level SDK never learns that the VPN is up, so a getUserLocation(mode: .auto) call your app makes itself treats the VPN as down

.legacy is a fallback, should the Low Level SDK's location caching across VPN connects cause problems. A change applies from the next call; nothing already pending is lost. The VPN state stays right across a change: a connect reported with .detailed is followed by a .vpnDisconnected with .legacy, and switching to .detailed while the VPN is connected reports .vpnConnected at once.

handle.networkChangeReporting = flags.legacyNetworkChangeReporting ? .legacy : .detailed

Showing the Wi-Fi network​

KapeNetworkHelper (part of KapeCore) publishes the Wi-Fi identity the SDK last sent, for display in your UI. It is optional: the SDK reports network changes whether or not you create it. Since it shows what the SDK sent, it shows no Wi-Fi network while the traffic goes over cellular, including behind a captive portal, nor while the device has no network.

import KapeCore

let networkHelper = KapeNetworkHelper(handle: handle)
networkHelper.start()

Call stop() when the helper is no longer needed:

networkHelper.stop()

Observing network info in SwiftUI​

KapeNetworkHelper is an ObservableObject with two published properties:

PropertyTypeDescription
ssidString?Name of the Wi-Fi network the traffic uses. nil while the traffic does not go over Wi-Fi (cellular, wired, or a Wi-Fi network behind an unpassed captive portal), while the device has no network, on tvOS, or without the prerequisites.
bssidString?Access point MAC address of that Wi-Fi network. nil in the same cases as ssid.
// In your view model
@Published private(set) var wifiSSID: String?

networkHelper.$ssid.assign(to: &$wifiSSID)
// In your SwiftUI view
Section("Network") {
LabeledContent("SSID") { Text(viewModel.wifiSSID ?? "–") }
}

Wi-Fi identity prerequisites​

The SDK reads the SSID and BSSID itself, but the OS reveals them only to an app that meets its conditions. Without them both are nil on Wi-Fi too. Network changes are still reported, but every Wi-Fi network of the same ISP then shares one Smart Location cache entry, and Wi-Fi shares it with cellular.

PlatformWhat your app needs
iOSThe wifi-info entitlement, and either its VPN profile installed or precise Location permission
macOSLocation Services permission
tvOSNot available: both are always nil

iOS. Add the entitlement to your app target's .entitlements file. In the Developer portal it is the Access Wi-Fi Information capability of the app's ID:

<key>com.apple.developer.networking.wifi-info</key>
<true/>

The entitlement alone is not enough: iOS also wants the app to have a VPN profile installed, or precise Location permission. So a new install reports no Wi-Fi identity until installProfile() or the first connect has added the profile, unless your app already has Location permission for another reason.

macOS. The SDK reads the Wi-Fi network through CoreWLAN, which needs no entitlement but reports the SSID and BSSID only to an app the user has allowed to use Location Services.

The SDK never asks for Location permission. If your app has it, or gains it, the SDK uses it from the next network or VPN state change on. If the OS stops revealing the SSID and BSSID while the device stays on Wi-Fi, for example because the permission was revoked, the SDK keeps reporting the last ones until the traffic leaves that Wi-Fi network.

warning

Do not instantiate KapeNetworkHelper in the PacketTunnel extension. The extension runs no Smart Location measurements and has a strict memory budget; the SDK does not monitor the network there.

Integration Rules​

Smart Location, ping and speed test measurements rest on two guarantees: results are cached per network, and no measurement runs through the VPN tunnel. The SDK keeps most of the rules behind them itself:

  • It runs one measurement at a time per KapeLocationService.
  • It measures nothing while the VPN is up or coming up, or while the user is signed out.
  • Every KapeVPNManager connect stops a running measurement before it starts the tunnel.
  • It reports every network change, with the current Wi-Fi identity, and every VPN state change.

What stays with your app​

RuleWhat your app does
Keep the Smart Location cacheNever delete the smart_location_results keychain item under your keychain_service: not on sign-out, app update or a "reset" feature. The cache is keyed by network, not by account, and the SDK expires entries itself. The SDK's own sign-out keeps it; deleting every item of the keychain service does not. Without it, every network has to be measured again.
Use one KapeLocationServiceCreate one instance and share it. Only requests to the same instance join or queue. Requests from two instances, or measurements your app runs through the Low Level SDK directly, compete for the SDK's single measurement slot, and the later one fails.
Connect through KapeVPNManagerOnly its connect stops a running measurement. A tunnel started by Connect on Demand, from iOS Settings or by your own Packet Tunnel code stops nothing.
Keep full measurements off the connect pathRun getSmartLocations() in the background while disconnected. A full measurement takes up to 30 s, so never await one between the user's tap and the connect.
Never connect to an arbitrary locationWhen your app picks the location itself, take it from fetchCachedSmartLocations() or the last ranking you showed, never from the first entry of allLocations. Or connect with .auto and let the SDK pick. See Connecting.
Treat expected errors as expectedCancellationError: a connect, sign-out or speed test stopped the measurement, not a failure to show. KapeVPNError.notAllowedWhileConnected: the VPN is up, so show the stored ranking. KapeVPNError.notAuthenticated: the user is signed out.
Meet the Wi-Fi prerequisitesOptional. Without them, results are stored per ISP instead of per Wi-Fi network. See Wi-Fi identity prerequisites.

Order of operations​

The user taps Connect

StepDone by
1. Stop running measurements and wait for themSDK, in every KapeVPNManager connect
2. Pick the location: the stored ranking, else a fast search, else the nearest locationsYour app, or the SDK with connect(mode: .auto)
3. Start the tunnelSDK
4. Once connected, call networkChanged(change: .vpnConnected)SDK

connect(mode: .auto) runs step 1 before step 2, so its pick never waits for a background measurement. Your app picks before it calls connect(to:), so read the stored ranking with fetchCachedSmartLocations(): it never measures, so it does not wait for a measurement that step 1 is about to stop.

The VPN disconnects

StepDone by
1. Call networkChanged(change: .vpnDisconnected)SDK, when the VPN reaches disconnected
2. Only then read Smart LocationsYour app: getSmartLocations()

A measurement waits for a pending networkChanged(change:) call, so your app can start it as soon as it sees .disconnected.

The network changes while the VPN is disconnected

StepDone by
1. Call networkChanged(change: .switched(…)) with the SSID and BSSIDSDK
2. Read Smart LocationsYour app: getSmartLocations()

getSmartLocations() returns the stored ranking for the new network, and measures only when that network has none yet.