A SwiftUI example app
Usage shows each verb on its own. This page puts them together in a small SwiftUI app,
so you can see where the WiDAS instance lives, how your user's access token reaches your Broker,
how status() drives the screen, and what happens when the user signs out.
It issues certificates through your Broker, the route we recommend.
The code targets iOS 15 or later. The parts you supply are your sign-in, your Broker's address, your
clientId in place of client-acme, and your Team ID in the Keychain access group in place of
<TeamID>.
This shows how the pieces fit together rather than being a library to drop in. Fit it to your own app's structure, and build and test it in your project before you ship it.
Prerequisites
- The SDK and its setup. Add the Swift Package and complete iOS setup: the Hotspot Configuration entitlement, the Keychain access group, and registering your Broker.
- Your Broker adapter. Copy
MyBrokerfrom ImplementBrokerinto your app target as it stands. The code below builds it withMyBroker(endpoint:userAccessToken:). - Your Broker. Running, registered with Wi-DAS, and reachable from your app behind your own sign-in. Brokered issuance covers what it does.
The example has four pieces:
| File | What it does |
|---|---|
AppSession.swift | Your own sign-in. You already have this; the example only needs three things from it. |
WiFiOnboarding.swift | Owns the one WiDAS instance and turns its verbs into state your views can watch. |
WiFiStatusView.swift | Shows the certificate's status, serial and expiry, with Connect and Disconnect. |
ExampleApp.swift | Wires it together: checks the status at launch and connects only if needed, rechecks on return to the foreground, and disconnects on sign-out. |
1. Your sign-in
Keep whatever sign-in your app already uses. The example needs three things from it: the signed-in user's ID, a way to get a current access token, and sign-out. Here they are as a sketch:
// AppSession.swift — a sketch of your own sign-in, not part of the SDK.
@MainActor
final class AppSession: ObservableObject {
/// The signed-in user's ID in your system, or nil when nobody is signed in.
@Published private(set) var userID: String?
/// A current access token for your API, refreshed first if it's close to expiring.
func freshAccessToken() async throws -> String {
fatalError("Replace with your own sign-in")
}
/// Signs the user out and sets `userID` to nil.
func signOut() async {
fatalError("Replace with your own sign-in")
}
}
Your Broker should work out who the user is from the access token, not trust the user ID the app sends alongside it.
2. The onboarding model
WiFiOnboarding is the only type that talks to the SDK. It builds one WiDAS instance with your
MyBroker adapter and publishes the latest status, a busy flag and a message for the user.
// WiFiOnboarding.swift
import Foundation
import os
// The SDK's types aren't marked Sendable. @preconcurrency keeps a Swift 6 build from failing on
// the hand-off when the main actor awaits them.
@preconcurrency import WiDAS
@MainActor
final class WiFiOnboarding: ObservableObject {
/// The latest status, or nil until the first check has finished.
@Published private(set) var status: WiDAS.Status?
/// A short message for the user after a failure, or nil.
@Published private(set) var message: String?
/// True while a connect or disconnect is running.
var isBusy: Bool { connectTask != nil || disconnectTask != nil }
var isConnected: Bool { status?.state == .valid && !isSomeoneElses }
var hasCertificate: Bool { status?.serial != nil }
/// True when the valid certificate on this device was issued to someone other than the
/// signed-in user. It doesn't count as connected.
var isSomeoneElses: Bool { status?.state == .valid && certificateUser != userID }
private let widas: WiDAS
private var userID: String?
@Published private var connectTask: Task<Void, Never>?
@Published private var disconnectTask: Task<Void, Never>?
/// Goes up each time a connect or disconnect starts, so refresh() can tell its reading is stale.
private var generation = 0
private let log = Logger(subsystem: "com.example.app", category: "wifi")
/// Who the certificate on this device was issued to. A certificate belongs to one user, so a
/// different user signing in gets their own.
private var certificateUser: String? {
get { UserDefaults.standard.string(forKey: "wifi.certificateUser") }
set { UserDefaults.standard.set(newValue, forKey: "wifi.certificateUser") }
}
/// Seconds to wait before each retry when your Broker or Wi-DAS can't be reached.
/// Three retries, then the user sees a message.
private static let retryDelays: [UInt64] = [2, 4, 8]
init(
clientId: String,
brokerEndpoint: URL,
keychainAccessGroup: String,
accessToken: @escaping () async throws -> String
) {
widas = WiDAS(
clientId: clientId,
broker: MyBroker(endpoint: brokerEndpoint, userAccessToken: accessToken),
baseURL: WiDAS.productionBaseURL,
keychainAccessGroup: keychainAccessGroup
)
}
/// Call when a user is signed in, including at launch with a restored session. Reads the
/// status, and connects only if there's no usable certificate for this user: each connect
/// issues a new one.
func start(user: String) async {
userID = user
await checkStatus(atLaunch: true)
}
/// Onboards, renews or recovers. Does nothing while another call is running.
func connect() async {
guard let userID, !isBusy else { return }
generation += 1
message = nil
let task = Task {
do {
try await connectWithRetry(user: userID)
certificateUser = userID
} catch {
show(error)
}
status = await widas.status()
connectTask = nil
}
connectTask = task // isBusy is true from here, before anything else gets to run
await task.value
}
/// Reads the status, and connects again if the certificate has expired, been revoked or was
/// issued to someone else. Leaves `.none` alone, so it doesn't undo a Disconnect.
func refresh() async {
await checkStatus(atLaunch: false)
}
/// Removes the Passpoint profile and the certificate from this device. If a removal is
/// already running, waits for that one instead of starting another.
func disconnect() async {
if disconnectTask == nil {
// Don't make the user wait out a connect that's still retrying.
let pendingConnect = connectTask
pendingConnect?.cancel()
generation += 1
message = nil
disconnectTask = Task {
await pendingConnect?.value
do {
try await widas.disconnect()
certificateUser = nil
} catch {
show(error)
}
status = await widas.status()
disconnectTask = nil
}
}
await disconnectTask?.value
}
/// Call before your own sign-out. Returns once the profile has been removed, or removal has failed.
func signOut() async {
userID = nil // no new connect or refresh from here on
await disconnect()
}
private func checkStatus(atLaunch: Bool) async {
guard userID != nil, !isBusy else { return }
let started = generation
let current = await widas.status()
// If a connect or disconnect started meanwhile, its own reading is the one to show.
guard userID != nil, !isBusy, generation == started else { return }
status = current
switch current.state {
case .expired, .revoked:
await connect()
case .none where atLaunch:
await connect()
case .valid where certificateUser != userID:
await connect() // issued to someone else, so this user gets their own
case .none, .valid:
break
}
}
private func connectWithRetry(user: String) async throws {
for delay in Self.retryDelays {
do {
try await widas.connect(user: user, requestedValidity: "P365D")
return
} catch WiDASError.network, WiDASError.serviceUnavailable {
// Temporary. Wait, then try again.
try await Task.sleep(nanoseconds: delay * NSEC_PER_SEC)
}
}
// The last attempt. Whatever it throws goes to the caller.
try await widas.connect(user: user, requestedValidity: "P365D")
}
private func show(_ error: Error) {
switch error {
case is CancellationError, WiDASError.cancelled:
// The retry wait or the connect was cancelled, usually by a sign-out. Nothing to say.
return
case let error as WiDASError:
log.error("Wi-DAS \(error.code, privacy: .public): \(error.localizedDescription, privacy: .private)")
message = Self.userMessage(for: error)
default:
log.error("Wi-DAS call failed: \(error.localizedDescription, privacy: .private)")
message = "Something went wrong setting up Wi-Fi. Please try again."
}
}
private static func userMessage(for error: WiDASError) -> String? {
switch error {
case .cancelled:
return nil
case .network, .serviceUnavailable:
return "We couldn't reach the Wi-Fi service. Check your connection and try again."
case .passpointInstallFailed:
return "The Wi-Fi profile couldn't be changed on this device. Please try again."
case .revoked:
return "Your Wi-Fi access has been withdrawn. Please contact support."
case .entitlementMissing, .issuanceRejected:
return "Wi-Fi setup isn't available for your account right now. Please contact support."
case .attestationUnavailable, .attestationRejected, .internalError:
// The attestation cases only arrive on the App Attest route; give them their own
// messages if you use it.
return "Something went wrong setting up Wi-Fi. Please contact support."
}
}
}
A few things worth knowing about how it behaves:
- The access token is fetched fresh every time.
MyBrokercalls theaccessTokenclosure each time it signs a request, so everyconnect(), and every retry inside it, picks up a current token from your sign-in. Nothing in the model stores a token. connect()runs off the main actor. The SDK's verbs aren't tied to any actor, so awaiting them from the main actor runs the key generation and network calls in the background. The code after eachawaitis back on the main actor, which is where the model publishes the result.- Retries are bounded.
networkandserviceUnavailableare temporary, so the model tries four times in all, waiting 2, 4 and then 8 seconds in between. If the last attempt fails too, the user sees a message, and the next launch, or a tap on Connect, tries again. Every other case is final for that call, so it goes straight to a message. - One call at a time.
isBusyis set before the firstawaitinconnect(), so the status checks at launch and on coming to the foreground can't both start a connect. While it's set,connect()andrefresh()do nothing, and a status check ignores a reading that a connect or disconnect overtook.disconnect()is the exception: it cancels a connect that's still running, so signing out never waits on retries, and a seconddisconnect()waits for the first rather than starting another.
3. The status view
The view reads everything from the model and sends Connect and Disconnect back to it. While a call is running, it shows a spinner and disables both buttons. Sign out is disabled while a sign-out is already under way.
// WiFiStatusView.swift
import SwiftUI
import WiDAS
struct WiFiStatusView: View {
@ObservedObject var wifi: WiFiOnboarding
let isSigningOut: Bool
let onSignOut: () -> Void
var body: some View {
Form {
Section {
row("Status", wifi.status.map { wifi.isSomeoneElses ? "Set up for another user" : label(for: $0.state) } ?? "Checking…")
row("Serial", wifi.status?.serial ?? "–")
row("Expires", wifi.status?.expiry?.formatted(date: .abbreviated, time: .omitted) ?? "–")
} header: {
Text("Wi-Fi")
} footer: {
if let message = wifi.message {
Text(message).foregroundColor(.red)
}
}
Section {
if wifi.isBusy {
HStack(spacing: 12) {
ProgressView()
Text("Working…").foregroundColor(.secondary)
}
}
// Every connect() issues a new certificate, so it only runs when the user asks.
// While connected it's "Reinstall", which puts back a profile deleted in Settings.
Button(wifi.isConnected ? "Reinstall" : "Connect") {
Task { await wifi.connect() }
}
.disabled(wifi.isBusy)
Button("Disconnect", role: .destructive) {
Task { await wifi.disconnect() }
}
.disabled(wifi.isBusy || !wifi.hasCertificate)
}
Section {
Button("Sign out", action: onSignOut)
.disabled(isSigningOut)
}
}
.refreshable { await wifi.refresh() }
}
private func row(_ title: String, _ value: String) -> some View {
HStack {
Text(title)
Spacer()
Text(value).foregroundColor(.secondary)
}
}
private func label(for state: WiDAS.Status.State) -> String {
switch state {
case .none: return "Not set up"
case .valid: return "Connected"
case .expired: return "Expired"
case .revoked: return "Revoked"
}
}
}
status() never throws and doesn't involve your Broker, so pull-to-refresh is cheap. Remember it's
advisory: the network is the real authority on whether a certificate still works.
4. Wire it into the app
Create the model once, next to your sign-in, and hand it your token provider. The root view then checks the status whenever a user is signed in and connects if there's no usable certificate, rechecks the status each time the app comes to the foreground, and disconnects before your own sign-out.
// ExampleApp.swift
import SwiftUI
@main
struct ExampleApp: App {
@StateObject private var session: AppSession
@StateObject private var wifi: WiFiOnboarding
init() {
let session = AppSession()
_session = StateObject(wrappedValue: session)
_wifi = StateObject(wrappedValue: WiFiOnboarding(
clientId: "client-acme",
brokerEndpoint: URL(string: "https://api.example.com/wi-das/certificates")!, // your Broker
keychainAccessGroup: "<TeamID>.com.apple.networkextensionsharing",
accessToken: { try await session.freshAccessToken() }
))
}
var body: some Scene {
WindowGroup {
RootView(session: session, wifi: wifi)
}
}
}
struct RootView: View {
@ObservedObject var session: AppSession
@ObservedObject var wifi: WiFiOnboarding
@Environment(\.scenePhase) private var scenePhase
@State private var isSigningOut = false
var body: some View {
Group {
if session.userID != nil {
WiFiStatusView(wifi: wifi, isSigningOut: isSigningOut) {
Task { await signOut() }
}
} else {
SignInView(session: session) // your own sign-in screen
}
}
// At launch with a restored session, and whenever a user signs in: connect if there's no
// usable certificate.
.task(id: session.userID) {
if let userID = session.userID {
await wifi.start(user: userID)
}
}
// Each time the app comes back: reconnect if the certificate expired or was revoked.
.task(id: scenePhase) {
if scenePhase == .active {
await wifi.refresh()
}
}
}
@MainActor
private func signOut() async {
guard !isSigningOut else { return } // a second tap while the first is still running
isSigningOut = true
await wifi.signOut() // remove the profile while we still know whose it is
await session.signOut()
isSigningOut = false
}
}
Each connect() issues a new certificate, so the app doesn't connect on every launch. It reads the
status first and connects only for .none, .expired or .revoked; connect() works out for
itself whether that's a first enrolment, a renewal or a recovery. Coming back to the foreground
reconnects only for .expired or .revoked, so a Disconnect sticks for the rest of the session. The
next launch finds .none and connects again, so if users can opt out, remember that in your app and
don't connect for them at launch. If you revoke a user on purpose, have your Broker refuse them too;
otherwise the app issues them a new certificate the next time it comes to the foreground.
The model also remembers which user the certificate was issued to. A certificate belongs to one user,
so a different user signing in on the same device gets their own: the model connects whenever it finds
someone else's certificate, at launch or on coming back to the foreground, and shows it as not
connected until then. The stored user starts empty, so the first launch after you ship this, or after
a reinstall (the SDK's Keychain state survives one, UserDefaults doesn't), issues one new
certificate. That's expected.
Disconnect before your own sign-out so the next person to sign in on the device doesn't inherit the
last user's Wi-Fi access. wifi.signOut() stops any connect that's still running and waits for the
removal to finish, including one the user started with Disconnect, so your sign-out always runs
after it, and only once. If removal fails, the SDK keeps the certificate's details, so the status
still shows it and a later disconnect() can try again.
Error handling
The model sorts failures into three kinds:
- Temporary —
networkandserviceUnavailable. Retried with backoff, then shown as a message. - Nothing to report —
cancelled, or a cancelled retry wait. The user walked away, or signed out mid-connect. Nothing is logged. - Needs a fix — everything else. The user gets a short message, and the case's
codeand developer description go to your log, with the description marked private.attestationUnavailableandattestationRejectedcan't happen when you issue through your Broker, so the example folds them into the general message, as it does any error that isn't aWiDASError.
Change the messages to suit your app's voice. Error handling explains each case and what usually causes it, and Troubleshooting walks through the fixes.
Use App Attest instead
To issue with App Attest, leave out broker: when you build the WiDAS instance, drop
brokerEndpoint and accessToken from the model's initialiser, and stop passing them from
ExampleApp.init. The SDK then vouches for each request with App Attest
(Configure for App Attest instead). On this route
attestationUnavailable and attestationRejected can arrive, so give each its own message in
userMessage(for:) rather than the general one. Everything else on this page stays the same. We'll
remove this route in the near future, so use it only for an app that already depends on it. It also
needs the App Attest capability and a registered app identity; see Setup.
The Simulator can't join a Passpoint network, so confirm onboarding on a physical device.