---
title: "Quickstart: iOS and Swift"
overline: QUICKSTART
nav: iOS / Swift
updated: 2026-12
minutes: 5
next: multi-app-sync
---

# 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.

> **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 at `https://kovlet.com`.
- **A local `kovletd --dev`**, from the `ghcr.io/kovlethq/kovletd` Docker image or the `kovletd` binary. [Run Kovlet locally](https://kovlet.com/docs/run-locally) starts it and shows how to approve your app from the terminal.

## 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`:

```swift title="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`.

## 2. Sign in

```swift title="TodosApp.swift" hl="3,5"
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.
- `ASWebAuthenticationSession` catches the redirect itself, so nothing needs registering in `Info.plist`.

Other sign-in methods:

- `.device(onCode:)` is the device flow. Show `code.userCode` and `code.verificationURI` to 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 key](/docs/glossary#device-key "A 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 `isSignedIn` before calling `signIn`.

## 3. Pick or create a space

A [Data Space](/docs/glossary#data-space "A 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:

```swift
let spaceId = try await kovlet.spaces.findOrCreate(name: "Todos").id
```

- `spaces.list()` returns the spaces the person granted this app, plus `requestable` and `canCreate`.
- `spaces.create(name:slug:)` makes a new one.
- Neither needs the console or another sign-in.

## 4. Sync a table

Open the space with your tables, then read and write typed rows:

```swift title="TodosApp.swift" hl="7-8,11,13"
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 typed `upsert`, `all` and `observe()`, an `AsyncStream` of rows.

> **You should see**
>
> - The system sign-in sheet on the first launch.
> - Once you approve the app, `todos.observe()` yields "Buy milk" at once.
> - Then every row other apps wrote to the same `Todos` space, such as the ones from the [web](https://kovlet.com/docs/quickstart-web) or [Node](https://kovlet.com/docs/quickstart-node) quickstart.
> - Later launches skip the sheet.

### How reads and writes work

- Writes go to the local store first, then sync.
- `upsert(row)` sends the row's fields as a patch. A `nil` optional is left out, so clear a field with `update(id, fields: ["note": .null])`.
- `all()`, `get(_:)`, `delete(_:)` and `restore(_:)` 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:` to `open` with a `KovletDataStore`. Its `apply(_:)` receives each merged `ChangeBatch` in order.

## 5. Files (optional)

```swift
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:)` and `delete(id:)` cover the rest.

## 6. Status and lifecycle (optional)

```swift
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) }
```

- `scenePhaseChanged` pauses sync in the background and reconnects in the foreground.
- For background refresh, register a `BGAppRefreshTask` and call `kovlet.handle(task)`. It runs `syncOnce(deadline: 25)`.
- `kovlet.events` streams rejected writes, errors and quota warnings.

## 7. Live queries (optional)

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 `.ref` columns, forward or backward.
- `$` holds `where`, `order`, `limit` and `fields`.

The [query language](https://kovlet.com/docs/protocol#175-the-query-language) reference has the details.

```swift hl="1-3"
let open = try space.subscribe([
    "todos": ["$": ["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 `.purge` change for your own `KovletDataStore`).
- **Restarts.** Subscriptions survive restarts and resume from their last cursor.
- **Status.** `try open.unsubscribe()` ends one. `open.status` shows `complete`, `more` and errors such as `invalid_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.

## 8. Atomic writes (optional)

`space.transact([...])` writes several rows all or nothing:

```swift
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.events` reports it as `.transaction(status: "rejected", …)`.

## 9. End users (public apps) (optional)

A public app can sign people in without a Kovlet account. These people are [end users](https://kovlet.com/docs/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.

```swift
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 view
```

How 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](https://kovlet.com/docs/rules) decide which rows arrive and which writes are accepted.
- `auth.signOut()` (or `kovlet.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](https://kovlet.com/docs/run-locally) starts `kovletd --dev` with Docker or the `kovletd` binary.

```sh
kovletd --dev --dev-auto-approve     # http://127.0.0.1:8080, approves device codes at once
```

```swift
let 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](https://kovlet.com/docs/quickstart-rest). The [sync protocol reference](https://kovlet.com/docs/protocol) covers every frame, merge rule and error.

## Next

- [Share live data between two AI-built apps](https://kovlet.com/docs/multi-app-sync): the tutorial that connects a second app to the same Data Space.
- [Upload and sync files](https://kovlet.com/docs/files): versions, moves and the Trash.
- [Let strangers sign in to your app (end users)](https://kovlet.com/docs/end-users): public apps with their own users.
- [/llms-full.txt](https://kovlet.com/llms-full.txt): the full reference.
