Skip to main content

Usage

All four verbs are async. connect() and disconnect() can throw a WiDASError; status() never does. There's also debugInfo(), which sits outside the flow and exists purely for support.

Implement Broker​

Skip this section if you're issuing through App Attest.

Broker is how the SDK reaches your Broker. It has one method:

public protocol Broker {
func sign(_ submission: SigningRequestSubmission) async throws -> IssuanceResponse
}

sign gets a SigningRequestSubmission carrying clientId, partnerUserId, csr, requestedValidity and deviceId. Send them to your Broker, which makes the certificate request and returns the Wi-DAS response. Turn that response into an IssuanceResponse.

The submission carries no Idempotency-Key. Your Broker makes that, because only your Broker knows which of its calls are retries.

When something fails, throw a BrokerError:

  • Your Broker answered with a refusal: throw BrokerError.refused(problemTitle:) with the problem title from the response, exactly as it arrived. The SDK maps it to a WiDASError, and matching is exact, so a trimmed or re-cased title lands on the generic issuanceRejected.
  • No usable answer arrived: throw BrokerError.unreachable(underlying:). The SDK reports it as network, which your app can retry. That includes a timeout (408), rate limit (429) or server error (5xx) that carries no problem title, such as an error page from a gateway in front of your Broker. A URLError you let escape is reported as network too, and a cancelled request as cancelled.

Most other errors you throw are reported as internalError.

Here's an implementation over URLSession, talking to a Broker endpoint you define (here POST /wi-das/certificates) that relays to Wi-DAS and passes its response back:

import Foundation
import WiDAS

struct MyBroker: Broker {
/// Your Broker's endpoint, for example https://api.example.com/wi-das/certificates
let endpoint: URL
/// Your own sign-in. The Broker should work out who the user is from this,
/// not trust partnerUserId as sent.
let userAccessToken: () async throws -> String

func sign(_ submission: SigningRequestSubmission) async throws -> IssuanceResponse {
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(try await userAccessToken())", forHTTPHeaderField: "Authorization")
request.httpBody = try JSONEncoder().encode([
"clientId": submission.clientId,
"partnerUserId": submission.partnerUserId,
"csr": submission.csr,
"requestedValidity": submission.requestedValidity ?? "P365D", // your default
"deviceId": submission.deviceId,
])

// A URLError escaping here is reported as `network`, or `cancelled` if the task was cancelled.
let (data, response) = try await URLSession.shared.data(for: request)

let status = (response as? HTTPURLResponse)?.statusCode ?? 0
guard (200..<300).contains(status) else {
let title = (try? JSONDecoder().decode(Problem.self, from: data))?.title
// A timeout, rate limit or server fault with no problem title (a gateway error page, say)
// is temporary. Reporting it as a refusal would tell the app not to retry.
if title == nil && (status >= 500 || status == 408 || status == 429) {
throw BrokerError.unreachable(underlying: nil)
}
throw BrokerError.refused(problemTitle: title)
}

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
guard let issued = try? decoder.decode(Issued.self, from: data) else {
throw BrokerError.refused(problemTitle: nil) // an answer we couldn't read
}

return IssuanceResponse(
serial: issued.serial,
clientCertificatePem: issued.certificatePem,
issuingCaPem: issued.chainPem,
serverCaPem: issued.serverCaPem,
passpoint: PasspointSettings(
friendlyName: issued.passpoint.friendlyName,
caCertName: issued.passpoint.caCertName,
certName: issued.passpoint.certName,
realm: issued.passpoint.realm,
homeFqdn: issued.passpoint.homeFqdn,
mcc: issued.passpoint.mcc,
mnc: issued.passpoint.mnc,
rcoi: issued.passpoint.rcoi),
notAfter: issued.notAfter,
deviceId: issued.deviceId)
}
}

private struct Problem: Decodable {
let title: String?
}

// The Wi-DAS certificate response, as your Broker passed it back.
private struct Issued: Decodable {
let serial: String
let deviceId: String?
let certificatePem: String
let chainPem: String
let serverCaPem: String
let notAfter: Date
let passpoint: Passpoint

struct Passpoint: Decodable {
let friendlyName: String
let caCertName: String
let certName: String
let realm: String
let homeFqdn: String
let mcc: String?
let mnc: String?
let rcoi: String?
}
}

Configure​

Create one WiDAS instance and hold onto it wherever your app keeps long-lived services. It ships no secret, so there's nothing sensitive to protect here.

import WiDAS

let widas = WiDAS(
clientId: "client-acme",
broker: MyBroker(endpoint: brokerEndpoint, userAccessToken: signIn.accessToken),
keychainAccessGroup: "<TeamID>.com.apple.networkextensionsharing"
)
ParameterRequiredNotes
clientId✅Your Wi-DAS-issued public client identifier.
broker✅Your Broker adapter.
keychainAccessGrouprecommendedShared group so the NetworkExtension can pair the client identity. nil uses the app default.

The instance stays on the brokered route for its lifetime. It never calls App Attest, and it doesn't fall back to App Attest if your Broker can't be reached.

Configure for App Attest instead​

Leave out broker: and the SDK vouches for each request with App Attest, talking to Wi-DAS directly. We'll remove this route in the near future, so use it only for an app that already depends on it. Your app needs the App Attest capability and a registered identity; see Setup.

let widas = WiDAS(
clientId: "client-acme",
keychainAccessGroup: "<TeamID>.com.apple.networkextensionsharing"
)

Everything below works the same on both routes.

Connect​

connect() onboards the user. Call it when status() reports .none, .expired or .revoked. requestedValidity is an ISO-8601 duration; Wi-DAS clamps it to policy.

do {
let result = try await widas.connect(user: "user-42", requestedValidity: "P365D")
print("Onboarded. Serial \(result.serial), expires \(result.notAfter)")
} catch let error as WiDASError {
handle(error) // see Error handling
}

ConnectionResult carries the certificate serial and its notAfter expiry.

Check status before you connect

connect() works out whether this is a first enrolment, a renewal or a recovery, so you don't track it. Calling it again is safe, but each call issues a new certificate through your Broker (or App Attest), so don't call it on every launch. Certificates last about a year: at launch, check status() first and connect only when there's no usable certificate.

status() reads what the SDK stored, so if the user deletes the Wi-Fi profile by hand it still reports .valid. Keep a Connect or Reinstall action in your UI even while connected, so the user can put the profile back; otherwise it comes back at the next renewal.

Status​

status() is advisory and never throws, so it's safe to call whenever you're rendering UI. The SDK asks Wi-DAS directly on both routes; your Broker isn't involved.

let status = await widas.status()
switch status.state {
case .none:
promptToConnect() // nothing installed yet
case .valid:
showConnected(expiry: status.expiry)
case .expired, .revoked:
try? await widas.connect(user: "user-42", requestedValidity: "P365D") // re-onboard
}

Status gives you state (.none/.valid/.expired/.revoked), the serial, and the expiry. Remember the network is the real authority here; status() is for the UI.

Disconnect​

Remove the installed profile when the user asks, or after a revoked result.

try await widas.disconnect()

With App Attest, the attested key sticks around, so a later connect() takes the fast assertion path.

Diagnostics​

debugInfo() sits outside the flow. It returns the configuration Wi-DAS resolved for your Client alongside what the device holds, as a payload you can send to support when the certificate installs and the device still won't join.

let info = try await widas.debugInfo() // nil unless your Client is in DevMode

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
if let info {
print(String(decoding: try encoder.encode(info), as: UTF8.self))
}

It only answers while your Client has DevMode enabled, which a Wi-DAS operator sets on request, so nil is the normal answer in production. It throws nothing but cancelled, and the payload carries no secrets, so you can send it as it stands. Full field reference in Diagnostics.

A complete launch flow​

func onLaunch(userID: String) async {
// Each connect() issues a new certificate, so only connect when there's no usable one.
// If a different user can sign in on this device, see the example app for handling that.
let status = await widas.status()
guard status.state != .valid else {
render(status) // already onboarded: nothing to issue
return
}

do {
// .none, .expired or .revoked: first run, renewal or recovery — one call.
try await widas.connect(user: userID, requestedValidity: "P365D")
} catch WiDASError.network, WiDASError.serviceUnavailable {
scheduleRetry() // your Broker or Wi-DAS couldn't be reached; try again later
} catch let error as WiDASError {
handle(error)
} catch {
// Unexpected.
}

render(await widas.status()) // reflect real state in the UI
}
connect() doesn't block the main actor

connect() does key generation, a round trip to your Broker (or App Attest), and network I/O. None of that runs on the main actor, so it's fine to await connect() from your UI code. Update your UI on the main actor once you have the result.

For the whole thing in a SwiftUI app, including the sign-in token, status in the UI and sign-out, see the example app.

Next: Error handling.