Quickstart: sync an iOS or macOS app with Kovlet
Add live sync that works offline to a SwiftUI app with the Kovlet Swift package. People sign in once, and your Codable rows stay in sync with every other app on the same Data Space.
On this page
What you'll build
- An iOS or macOS todo app whose rows sync with every other app on the same Data Space.
- Sign-in once, in the system sign-in sheet. The app then finds or creates its space on its own.
- Writes land on the device at once and sync in the background, offline too.
- Optional extras: files, live queries, all-or-nothing writes, and sign-in for people without a Kovlet account.
Prerequisites
You need a Kovlet server. Pick one:
- The hosted API at
https://api.kovlet.com. The free plan is enough for testing. You sign in on the console athttps://kovlet.com. - A local
kovletd --dev, from theghcr.io/kovlethq/kovletdDocker image or thekovletdbinary. Run Kovlet locally starts it and shows how to approve your app from the terminal.
Step 1: Install
Add the Kovlet Swift package (https://github.com/kovlethq/kovlet-swift). In Xcode, use *File > Add Package Dependencies…*. Or add it in Package.swift:
.package(url: "https://github.com/kovlethq/kovlet-swift", from: "0.1.0")Then add the Kovlet library to your target.
Requirements: iOS 15+ or macOS 12+, and Swift 5.9+ (Xcode 15+).
Note The Swift layer has not yet been compiled or run on a Mac. Expect small fixes on the first build.
By default, the client talks to https://api.kovlet.com and opens sign-in and consent on https://kovlet.com.
Step 2: Sign in
import Kovlet
let kovlet = try KovletClient(appName: "Todos")
if !kovlet.isSignedIn {
try await kovlet.signIn(.webAuthentication(callbackScheme: "com.example.todos"))
}KovletClient(appName:) creates the client. signIn(.webAuthentication(callbackScheme:)) signs in with PKCE, the standard browser sign-in for apps, inside ASWebAuthenticationSession.
- The redirect is
<scheme>:/kovlet/callback. - Use a reverse-DNS scheme such as your bundle ID. Kovlet only accepts private-use schemes of that form.
ASWebAuthenticationSessioncatches the redirect itself, so nothing needs registering inInfo.plist.
Other sign-in methods:
.device(onCode:)is the device flow. Showcode.userCodeandcode.verificationURIto the person..token(_:)..machineKey(_:clientId:).
Sign in once. The app stays signed in across launches.
- Session tokens refresh themselves. They're kept in the Keychain (
<bundle id>.kovlet, after first unlock, this device only). - The device keyA key pair the app creates and can't export. It binds a session to one device. lives in the Secure Enclave (a software Keychain key in the Simulator).
- Check
isSignedInbefore callingsignIn.
Step 3: Pick or create a space
A Data SpaceA set of typed tables plus a tree of files, shared by every app with access to it. holds your tables and files. This line finds the space named "Todos", or creates it:
let spaceId = try await kovlet.spaces.findOrCreate(name: "Todos").idspaces.list()returns the spaces the person granted this app, plusrequestableandcanCreate.spaces.create(name:slug:)makes a new one.- Neither needs the console or another sign-in.
Step 4: Sync a table
Open the space with your tables, then read and write typed rows:
struct Todo: Codable, Identifiable {
var id: String
var title: String
var done: Bool
}
let space = try kovlet.open(spaceId, tables: [.init("todos", ["title": .string, "done": .boolean])])
let todos = space.table("todos", as: Todo.self)
Task { @MainActor in
for await rows in todos.observe() { self.todos = rows } // every local and remote change
}
try todos.upsert(Todo(id: UUID().uuidString, title: "Buy milk", done: false))open(_:tables:)declares the tables.space.table("todos", as: Todo.self)gives typedupsert,allandobserve(), anAsyncStreamof rows.
You should see
How reads and writes work
- Writes go to the local store first, then sync.
upsert(row)sends the row's fields as a patch. Aniloptional is left out, so clear a field withupdate(id, fields: ["note": .null]).all(),get(_:),delete(_:)andrestore(_:)do what they say.- Fields merge per field, and the later write wins.
- Column types:
.string,.number,.boolean,.datetime,.json,.fileRef,.ref("table"), each with.optional. New tables and optional columns are created on open. - To keep your own database (Core Data, GRDB, SwiftData) as the source of truth, pass
store:toopenwith aKovletDataStore. Itsapply(_:)receives each mergedChangeBatchin order.
Step 5: FilesOptional
let f = try space.files.put(path: "photos/receipt.jpg", data: jpegData, mimeType: "image/jpeg")
try todos.update(todoId, fields: ["photo": .string(f.id)]) // a .fileRef column
_ = try await space.files.download(id: f.id, to: localURL) // checks the SHA-256- Uploads are staged and sent in the background, so they work offline.
put(path:contentsOf:mimeType:)streams from a file URL.files.list(prefix:),move(id:to:)anddelete(id:)cover the rest.
Step 6: Status and lifecycleOptional
Task { @MainActor in for await s in kovlet.status { self.sync = "\(s.state.rawValue), \(s.pending) pending" } }
WindowGroup { ContentView() }
.onChange(of: scenePhase) { phase in kovlet.scenePhaseChanged(phase) }
// Or, as a View modifier on the root view:
WindowGroup { ContentView().kovletLifecycle(kovlet) }scenePhaseChangedpauses sync in the background and reconnects in the foreground.- For background refresh, register a
BGAppRefreshTaskand callkovlet.handle(task). It runssyncOnce(deadline: 25). kovlet.eventsstreams rejected writes, errors and quota warnings.
Step 7: Live queriesOptional
A live query keeps a result up to date as data changes. The client speaks sync protocol 2, where one socket per space carries many subscriptions.
A query is a JSON tree, like InstaQL:
- Top-level keys are tables.
- Nested keys follow
.refcolumns, forward or backward. $holdswhere,order,limitandfields.
The query language reference has the details.
let open = try space.subscribe([
"todos": ["quot;: ["where": ["done": false], "order": ["createdAt": "desc"], "limit": 50], "owner": [:]],
])
Task { @MainActor in
for await result in open.results() { self.todos = result.data["todos"] ?? [] } // rows, with `owner` nested
}- Full or partial copy.
open(_:tables:)keeps a full replica and runs queries locally.openQuery(_:tables:)keeps a partial replica: the server sends only the rows your subscriptions match. A row no subscription holds any more leaves the store (a.purgechange for your ownKovletDataStore). - Restarts. Subscriptions survive restarts and resume from their last cursor.
- Status.
try open.unsubscribe()ends one.open.statusshowscomplete,moreand errors such asinvalid_query. - One-off queries.
space.query([...])runs a query once over the local store, offline too, with the same matcher as the server.try await space.queryRemote([...])asks the server.
Step 8: Atomic writesOptional
space.transact([...]) writes several rows all or nothing:
let tx = try space.transact([
.upsert(table: "teams", id: teamId, fields: ["name": "Core"]),
.upsert(table: "members", id: memberId, fields: ["team": .string(teamId), "role": "owner"]),
])
try await tx.settled() // "applied", or throws the rejection- The writes apply locally at once and go to the server as one batch. The server applies all of them or none.
- If it rejects the batch, every write rolls back together.
- Queued writes to rows the batch created roll back too (
dependency_rejected). kovlet.eventsreports it as.transaction(status: "rejected", …).
Step 9: End users (public apps)Optional
A public app can sign people in without a Kovlet account. These people are end users. They can sign in with an email code, OAuth, an ID token or as a guest. A space owner turns end-user sign-in on for your app in the console. appId is your app's public ID.
let auth = kovlet.endUsers(spaceId: spaceId, appId: "app_…")
try await auth.sendMagicCode(to: email)
try await auth.signIn(email: email, code: code) // or signInAsGuest(), signIn(idToken:provider:)
// try await auth.signInWithOAuth(provider: "apple", redirectURI: "com.example.todos:/oauth", callbackScheme: "com.example.todos")
let space = try kovlet.openQuery(spaceId, tables: tables)
let mine = try space.subscribe(["todos": [:]]) // only the rows the space's rules let them viewHow end-user sessions behave:
- The session is bound to the device key and refreshes by itself.
- End users always sync over protocol 2 with query subscriptions.
- The space's rules decide which rows arrive and which writes are accepted.
auth.signOut()(orkovlet.signOut()) forgets every open space's synced rows and queued writes, so the next person on the device starts clean.
Local development
Run Kovlet locally starts kovletd --dev with Docker or the kovletd binary.
kovletd --dev --dev-auto-approve # http://127.0.0.1:8080, approves device codes at oncelet kovlet = try KovletClient(appName: "Todos", baseURL: URL(string: "http://localhost:8080"))
try await kovlet.signIn(.device(onCode: { code in print("Approve \(code.userCode)") }))Allow local networking in Info.plist (NSAppTransportSecurity > NSAllowsLocalNetworking). The Simulator shares the Mac's network, so localhost is the Mac.
Without the SDK
A Swift app can also talk to Kovlet directly with URLSession, without the package. It uses device-code or PKCE sign-in, REST for spaces and reads, and URLSessionWebSocketTask for writes and live sync. Start with the REST + WebSocket quickstart. The sync protocol reference covers every frame, merge rule and error.
Next
- Share live data between two AI-built apps: the tutorial that connects a second app to the same Data Space.
- Upload and sync files: versions, moves and the Trash.
- Let strangers sign in to your app (end users): public apps with their own users.
- /llms-full.txt: the full reference.
Ready to try it? Start free. No credit card, no API keys.
For coding agents: this page is also Markdown. Add .md to the URL or send Accept: text/markdown. The full reference is at /llms-full.txt.