Call lunas from Swift
Create a Swift client, call handlers, follow live queries in SwiftUI, queue writes offline and handle failed calls.
An iOS or macOS app needs to call handlers and keep its screens in step with a luna’s data. The Luna Swift package does both over one WebSocket that it opens when needed and reopens after a drop.
Create a client
ClientOptions(url:key:) takes the environment’s URL and a publishable key. Set any other option on it, then make one LunaClient for the whole app.
import Foundation
import Luna
let client: LunaClient = {
var options = ClientOptions(url: URL(string: "<LUNA_URL>")!, key: "<LUNA_KEY>")
options.callTimeout = .seconds(10)
return LunaClient(options)
}()
| Option | Does |
|---|---|
token |
A secret token instead of a key, for your own tools and never for an app |
headers |
Extra request headers |
params |
Query parameters for each new connection, for onBeforeConnect to read. Asked again on every reconnect |
callTimeout |
How long a call may take, waiting to connect included. 30 seconds by default |
keepAlive |
How long a query nobody watches stays live and cached. 10 seconds by default |
settle |
How long a confirmed optimistic write stays shown over queries of other lunas. 1 second by default |
multiplex |
One WebSocket for all lunas, true by default |
store, optimistic |
Keep results and queued writes between runs |
Call a handler
client.luna(type, key...) returns a LunaHandle. mutate calls a handler and read calls one once without following it. Arguments are JSON, written as literals.
struct Item: Codable, Sendable, Hashable {
let id: Int
let text: String
}
let list = client.luna("List", "groceries")
try await list.mutate("add", ["text": "milk"])
let items = try await list.read("all", as: [Item].self)
Without as: or returning:, a call returns JSON. Pass a value from a variable as .string(text). Calls run on the main actor, and calls to one luna run in the order you make them.
Follow a query in SwiftUI
observe returns a query as an observable value. Hold it in @State and the view follows it for as long as it is held.
import Luna
import SwiftUI
struct GroceriesView: View {
@State private var items = client.luna("List", "groceries").observe("all", as: [Item].self)
var body: some View {
List(items.data ?? [], id: \.id) { item in
Text(item.text)
}
}
}
status is .loading, .ready or .error, and stale is true while the connection is down. Outside SwiftUI, query(_:_:as:) returns a LiveQuery whose updates is an AsyncStream of each new state. Subscribe to a query explains what brings a new result.
Show a write at once
The trailing closure of mutate is an optimistic update. It changes what live queries show until a live result includes the write, and it is removed if the call fails.
let all = list.query("all", as: [Item].self)
try await list.mutate("add", ["text": "eggs"]) { local in
local.update(all) { $0 + [Item(id: -1, text: "eggs")] }
}
Hear pushes and follow streams
on(_:as:_:) hears a luna’s pushes, and observeStream(_:as:) reads a stream as it grows. observeConnection() follows the connection’s status. Each keeps going for as long as you hold what it returns, and on also stops when you call cancel().
let room = client.luna("Room", "r1")
let joined = room.on("joined", as: String.self) { name in print("\(name) joined") }
Push to connected apps and Follow a stream from an app cover the luna’s side.
Queue writes offline
Set store to a DiskStore, which keeps results and queued writes in the app’s Application Support folder. Use one for each account.
var options = ClientOptions(url: URL(string: "<LUNA_URL>")!, key: "<LUNA_KEY>")
options.store = try DiskStore(account: "ann")
options.optimistic["addItem"] = { local, luna, args in
let text = (try? args["text"]?.decode(as: String.self)) ?? ""
local.update(luna.query("all", as: [Item].self)) { $0 + [Item(id: -1, text: text)] }
}
let client = LunaClient(options)
try client.luna("List", "groceries").enqueue("add", ["text": "milk"], optimistic: "addItem")
writes, retryWrite, discardWrite, resumeWrites and wipe() work as they do in TypeScript. Work offline explains the order writes run in and what happens to one the luna refuses.
Handle a failed call
A failed call throws a LunaError with code, message and data. The codes are the same as in Call lunas from TypeScript.
do {
try await list.mutate("add", ["text": "milk"])
} catch let error as LunaError where error.code == "Timeout" {
print("No answer yet. The item may still be added.")
}
A handler that answers with an HTTP status of 400 or above throws an HTTPError instead. Read such a handler’s status and headers with response.
Next steps
- Generate a typed client gives each handler a Swift method.
- Swift quickstart runs a first call from a Mac.
- Swift client lists every type and method.