Skip to content

Concepts

Connecting to SurrealDB

The Swift SDK provides two transports: an HTTP client and a WebSocket client. Both share the same querying and CRUD API, and the WebSocket client additionally supports live queries. The methods below are available on both clients.

Method

Description

client.connect()

Connects the client to the endpoint it was configured with

client.use(namespace, database)

Switches to a specific namespace and database

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

Connects the client to the endpoint it was configured with.

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

Switches the connection to a specific namespace and database. Once connected, select the namespace and database your queries should run against.

Method Syntax
try await client.use(namespace: ns, database: db)
ArgumentDescription
namespace (required)The namespace to switch to.
database (required)The database to switch to.
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?

Last updated