• Start

Languages

/

Swift

/

Concepts

Connecting to SurrealDB

Learn how to connect to SurrealDB over HTTP or WebSocket and configure the client in the Swift SDK.

The Swift SDK provides two transports: an HTTP client and a WebSocket client. Both share the same querying and CRUD API; the WebSocket client additionally supports live queries.

SurrealHTTPClient connects over HTTP and is the simplest choice for request/response workloads.

let client = try SurrealHTTPClient(endpoint: "http://localhost:8000")
try await client.connect()
defer { Task { await client.close() } }

SurrealWebSocketClient connects over WebSocket and is required for live queries. It can also automatically reconnect when a connection is dropped.

let client = try SurrealWebSocketClient(
endpoint: "ws://localhost:8000",
websocketOptions: SurrealWebSocketOptions(
reconnectEnabled: true,
maxReconnectAttempts: 8,
reconnectBaseDelay: 0.5
)
)
try await client.connect()
defer { Task { await client.close() } }

Once connected, select the namespace and database your queries should run against:

try await client.use(namespace: "myapp", database: "mydb")

Common options shared by both the HTTP and WebSocket clients:

SurrealClientOptions(
requestTimeout: 20,
pingInterval: 30
)

Reconnection behaviour for the WebSocket client:

SurrealWebSocketOptions(
reconnectEnabled: true,
maxReconnectAttempts: 8,
reconnectBaseDelay: 0.5
)

Always close the client when you are done to release the underlying connection:

await client.close()

Was this page helpful?