Skip to content
QwryAI
Documentation
Pages

iOS SDK

SwiftUI

Build chat screens with ConversationState and ConversationListState, observable state that streams into your views

The SDK ships two @Observable classes for SwiftUI. They call QwryClient for you, keep the messages or conversations in a list, and update it on the main actor as answers stream in.

Why use these?

A chat screen built by hand has to add the user's bubble, show a placeholder while the agent writes, join the text pieces together, swap in the finished message and page through history. These two classes do that work:

TypeUse it for
ConversationStateOne chat screen: messages, streaming, retry and earlier history.
ConversationListStateA list of the user's conversations, a page at a time.

Both are @MainActor @Observable final classes, so SwiftUI redraws when they change. Keep them in @State, in a view model or in the environment, whichever your app already uses.

ConversationState

@MainActor @Observable final class ConversationState

init

Swift
public init(client: QwryClient, conversationId: String? = nil)
ParameterTypeRequiredDescription
clientQwryClientYesThe client to send through. Register your tools on it first.
conversationIdString?NoA conversation to continue. Leave it nil to start a new one on the first send.

A complete chat screen

Swift
import SwiftUI
import QwrySDK

struct ChatScreen: View {
    @State private var chat: ConversationState
    @State private var draft = ""

    init(client: QwryClient, conversationId: String? = nil) {
        _chat = State(initialValue: ConversationState(client: client, conversationId: conversationId))
    }

    var body: some View {
        VStack(spacing: 0) {
            ScrollViewReader { proxy in
                List {
                    if chat.hasEarlier {
                        ProgressView()
                            .frame(maxWidth: .infinity)
                            .task { await chat.loadEarlier() }
                    }
                    ForEach(chat.messages) { message in
                        MessageRow(message: message) { id in
                            Task { await chat.retry(messageId: id) }
                        }
                        .id(message.id)
                    }
                }
                .onChange(of: chat.messages.count) {
                    withAnimation { proxy.scrollTo(chat.messages.last?.id) }
                }
            }
            if let error = chat.error {
                Text(error.localizedDescription)
                    .font(.footnote)
                    .foregroundStyle(.red)
            }
            HStack {
                TextField("Message", text: $draft)
                Button("Send") {
                    let text = draft
                    draft = ""
                    Task { await chat.send(text) }
                }
                .disabled(chat.isSending || draft.isEmpty)
            }
            .padding()
        }
        .task { await chat.load() }
    }
}

load() does nothing for a new conversation, so the same screen works for both new and existing chats.

Showing a message

Each item in messages is a Message. Use text for a simple bubble, or walk parts to show tool activity:

Swift
struct MessageRow: View {
    let message: Message
    let onRetry: (String) -> Void

    var body: some View {
        VStack(alignment: message.role == .user ? .trailing : .leading) {
            ForEach(Array(message.parts.enumerated()), id: \.offset) { _, part in
                switch part {
                case .text(let text):
                    Text(text.isEmpty ? "…" : text)
                case .toolCall(let call):
                    Label(call.name, systemImage: "wrench.and.screwdriver")
                        .font(.footnote.monospaced())
                case .toolResult(let result):
                    Label(result.output["error"] == nil ? "Done" : "Failed",
                          systemImage: result.output["error"] == nil ? "checkmark.circle" : "xmark.circle")
                        .font(.footnote)
                }
            }
            if message.role == .assistant, !message.id.hasPrefix("pending-") {
                Button("Regenerate") { onRetry(message.id) }
                    .font(.caption)
            }
        }
    }
}

What you can read

PropertyTypeDescription
messages[Message]The messages to show, oldest first.
isSendingBooltrue from send or retry until the answer is complete. Disable your send button.
errorQwryError?Why the last send, retry or history load failed. The next one clears it.
conversationIdString?The conversation shown. Set after the first answer.
hasEarlierBoolOlder messages remain to load with loadEarlier().

You can't set these directly. Use the methods below.

send

Swift
public func send(_ text: String) async

Adds the user's message, adds an empty agent bubble, streams the answer into it and swaps in the finished message. It never throws: a failure removes the agent bubble and sets error.

Swift
Task { await chat.send(text) }

When conversationId is nil, send starts a new conversation, whatever conversation the client used last. The ID of that conversation is kept from the first answer on.

retry

Swift
public func retry(messageId: String) async

Asks the agent to answer again. That message and everything after it are removed from messages, then the new answer streams in.

Swift
Button("Regenerate") {
    Task { await chat.retry(messageId: message.id) }
}

The call does nothing when there's no conversation yet, or when messageId isn't in messages.

load

Swift
public func load() async

Replaces messages with the latest page of the conversation. It does nothing when conversationId is nil. Use it when you open a conversation from a list:

Swift
ChatScreen(client: client, conversationId: conversation.id)
    // ChatScreen calls chat.load() in .task

loadEarlier

Swift
public func loadEarlier() async

Loads the page before the oldest message shown and adds it to the top. It does nothing while hasEarlier is false.

ConversationListState

@MainActor @Observable final class ConversationListState

The user's conversations, most recently active first, loaded a page at a time.

Swift
public init(client: QwryClient)
PropertyTypeDescription
conversations[Conversation]The conversations loaded so far, most recently active first.
hasMoreBoolThere are more pages to load.
errorQwryError?Why the last load failed. The next load clears it.

load

Swift
public func load() async

Loads the first page and replaces conversations. Use it for the first load and for pull to refresh.

loadMore

Swift
public func loadMore() async

Adds the next page to the list. It does nothing while hasMore is false.

Swift
struct ConversationsScreen: View {
    let client: QwryClient
    @State private var list: ConversationListState

    init(client: QwryClient) {
        self.client = client
        _list = State(initialValue: ConversationListState(client: client))
    }

    var body: some View {
        List {
            ForEach(list.conversations) { conversation in
                NavigationLink(conversation.title ?? "New conversation") {
                    ChatScreen(client: client, conversationId: conversation.id)
                }
            }
            if list.hasMore {
                ProgressView()
                    .task { await list.loadMore() }
            }
        }
        .task { await list.load() }
        .refreshable { await list.load() }
    }
}

Using UIKit

Neither class depends on SwiftUI. In UIKit you can watch them with withObservationTracking, or skip them and call client.send(_:conversationId:configure:) yourself, hopping to the main actor inside the handlers:

Swift
Task {
    do {
        let response = try await client.send(text) { handlers in
            handlers.onTextDelta = { piece in
                Task { @MainActor in self.appendToBubble(piece) }
            }
        }
        self.finish(response)
    } catch {
        self.showError(error)
    }
}

Explore the documentation