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()

Error Handling

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

do {
    let response = try await client.chatCompletions(payload)
} catch let error as NRouterError {
    switch error {
    case .guardrailBlocked(let msg): print("Guardrail blocked: \(msg)")
    case .authenticationFailed: print("Invalid virtual key.")
    case .insufficientCredits: print("Account budget exhausted.")
    case .rateLimited(let sec): print("Rate limited: retry after \(sec ?? 1)s.")
    case .serverError(let code, let msg): print("Gateway error [\(code)]: \(msg)")
    case .networkError(let err): print("Transport error: \(err.localizedDescription)")
    }
}

Next Steps

Was this page helpful?