Swift applications
A Swift application can use Modem’s customer REST API and gateway directly. The wire operations are the same as the JavaScript SDK; do not assume a separate native SDK or copy JavaScript SDK state management into networking callbacks without coordinating it.
Establish a customer session
Configure an identity provider for your Modem project. Obtain that provider’s ID token using its native sign-in integration, then send it to the project identification endpoint. The JSON field is jwtToken.
import Foundation
struct CustomerSession: Codable {
let accessToken: String
let refreshToken: String
let customerId: String
let sandboxMode: Bool
}
func identify(projectId: String, identityToken: String) async throws -> CustomerSession {
let url = URL(string: "https://preternatural.ai/api/client/projects/\(projectId)/identify")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONSerialization.data(withJSONObject: ["jwtToken": identityToken])
let (data, response) = try await URLSession.shared.data(for: request)
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
throw URLError(.userAuthenticationRequired)
}
return try JSONDecoder().decode(CustomerSession.self, from: data)
}Success returns the session fields directly, not an extra data wrapper. Keep the project ID with the stored session. Persist tokens in the platform’s credential storage, not application logs or a public preferences file. Decode the error response for an actionable message and request ID; see REST conventions.
Refresh with POST /api/client/refresh and JSON { "refreshToken": "…" }. The response contains a replacement accessToken; retain the refresh token and customer/project/mode. Serialize concurrent renewals and discard responses belonging to a session that was replaced. A refused refresh requires a new sign-in; an arbitrary network failure does not prove expiry.
Stream chat text
Use the current access token and all request scope headers. This example forwards raw SSE lines so a parser can assemble events:
func streamChat(
session: CustomerSession,
projectId: String,
productId: String,
prompt: String,
receiveLine: (String) async throws -> Void
) async throws {
var request = URLRequest(url: URL(string: "https://gateway.preternatural.ai/v1/chat/completions")!)
request.httpMethod = "POST"
let headers = [
"Content-Type": "application/json",
"Accept": "text/event-stream",
"x-preternatural-auth-provider": "api-key",
"x-preternatural-api-key": session.accessToken,
"x-preternatural-customer-id": session.customerId,
"x-preternatural-project-id": projectId,
"x-preternatural-product-id": productId,
"x-preternatural-provider": "openai"
]
for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) }
request.httpBody = try JSONSerialization.data(withJSONObject: [
"model": "gpt-4o-mini",
"messages": [["role": "user", "content": prompt]],
"stream": true
])
let (bytes, response) = try await URLSession.shared.bytes(for: request)
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
throw URLError(.badServerResponse)
}
for try await line in bytes.lines {
try Task.checkCancellation()
try await receiveLine(line)
}
}URLSession.bytes(for:delegate:) supplies asynchronous response bytes. Its line sequence is not an SSE event parser: collect data: lines until the blank event separator, handle [DONE], decode chat deltas and detect error events. A stream ending without successful completion is incomplete even if HTTP headers were 200. Avoid concatenating every JSON payload as visible answer text.
Retain the Swift task so the UI can cancel it. Do not automatically retry after partial output or an ambiguous connection loss. Capture x-request-id without logging tokens. Follow gateway error handling for rate/allowance/access failures and gateway operations for interrupted streams.
StoreKit and customer products
Authenticate the customer before uploading a purchase. The receipt endpoint is POST /api/client/projects/{projectId}/customers/{customerId}/upload-receipt. It accepts signed StoreKit v2 transaction data, the legacy receipt/device pair, or consumable transaction IDs; sending an arbitrary receipt-shaped string does not establish a grant. Configure the project’s App Store billing provider and product mapping, then follow App Store purchases for validation, restoration and entitlement lifecycle.
Test on the actual app lifecycle: account switch, app relaunch, concurrent refresh, network interruption, cancellation, receipt restoration and Sandbox/Live separation. These HTTP examples do not provide those application policies automatically.