Browse documentation

Swift / iOS SDK

The official nRouter Swift SDK for iOS, macOS, watchOS, and visionOS with Swift Package Manager support, async/await, and zero third-party dependencies.

The official nRouter Swift SDK delivers zero-dependency Swift bindings for Apple platforms connecting to https://api.nrouter.ai/v1. Built on URLSession structured concurrency with async/await, it supports NROUTER_API_KEY authentication, real-time AsyncThrowingStream SSE streaming, and typed error handling across iOS 15+, macOS 12+, watchOS 8+, and visionOS 1+.

Installation

Add the dependency to Package.swift:

dependencies: [
    .package(url: "https://github.com/nRouterGateway/nrouter-sdk.git", from: "2.2.1")
]

Or add https://github.com/nRouterGateway/nrouter-sdk.git via Xcode File → Add Package Dependencies....

Chat Completion

Export your key for CLI/macOS, or pass it directly on iOS:

export NROUTER_API_KEY="sk-nrouter-xxxxxxxxxxxx"
import NRouter

let client = try NRouter(apiKey: "sk-nrouter-xxxxxxxxxxxx") // or try NRouter() from env
let payload: [String: Any] = [
    "model": "gpt-5.4-mini",
    "messages": [["role": "user", "content": "Explain Swift concurrency."]],
    "max_completion_tokens": 512
]

let result = try await client.chatCompletions(payload)
if let choices = result["choices"] as? [[String: Any]],
   let content = (choices.first?["message"] as? [String: Any])?["content"] as? String {
    print(content)
}

SSE Streaming

import NRouter

let stream = try await client.chatCompletionsStream([
    "model": "claude-haiku-4-5-20251001",
    "messages": [["role": "user", "content": "Write a haiku."]],
    "stream": true
])

for try await chunk in stream {
    if let delta = chunk.deltaContent {
        print(delta, terminator: "")
    }
}
print()

Per-Request Routing & nrouter/auto

Send "model": "nrouter/auto" and override the preference per call with "nrouter_optimize" ("quality" | "balanced" | "cost") and "nrouter_cost_band" ("low" | "mid" | "high", under "cost" only) — see Per-Request Options:

let autoResult = try await client.chatCompletions([
    "model": "nrouter/auto",
    "messages": [["role": "user", "content": "Summarize this incident report."]],
    "nrouter_optimize": "balanced"
])

Error Handling

Gateway refusals map to NRouterError cases — see Errors & Rate Limits:

do {
    let response = try await client.chatCompletions(payload)
} catch let error as NRouterError {
    switch error {
    case .request(let body): print("Request error [\(body.code ?? "invalid_request")]: \(body.message)") // invalid_request, cost_band_unsatisfiable
    case .guardrailBlocked(let body): print("Guardrail blocked: \(body.message)")
    case .authentication: print("Invalid virtual key.")
    case .credit, .budgetExceeded: print("Account balance or budget ceiling exhausted.")
    case .rateLimit(let body): print("Rate limited: retry after \(body.retryAfter ?? 1)s.")
    case .service(let body): print("Gateway error: \(body.message)")
    default: print("Error: \(error)")
    }
}

Next Steps

Was this page helpful?