# 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: | Type | Use it for | | - | - | | `ConversationState` | One chat screen: messages, streaming, retry and earlier history. | | `ConversationListState` | A list of the user's conversations, a page at a time. | Both are `@MainActor @Observable final class`es, 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) ``` | Parameter | Type | Required | Description | | - | - | - | - | | `client` | `QwryClient` | Yes | The client to send through. Register your tools on it first. | | `conversationId` | `String?` | No | A 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`](/docs/ios-sdk/chat-response). 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 | Property | Type | Description | | - | - | - | | `messages` | `[Message]` | The messages to show, oldest first. | | `isSending` | `Bool` | `true` from `send` or `retry` until the answer is complete. Disable your send button. | | `error` | `QwryError?` | Why the last `send`, `retry` or history load failed. The next one clears it. | | `conversationId` | `String?` | The conversation shown. Set after the first answer. | | `hasEarlier` | `Bool` | Older messages remain to load with `loadEarlier()`. | You can't set these directly. Use the methods below. > [!NOTE] > > While an answer streams, the agent's bubble has a temporary ID that starts with `pending-`, and the user's message has one that starts with `local-`. When the answer finishes, the bubble is replaced by the finished message with its real ID. Only pass real agent message IDs to `retry(messageId:)`. ### 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`. > [!TIP] > > To start a new chat, or after `client.logout()`, create a new `ConversationState` instead of reusing the old one. A new state starts with an empty list and no conversation. ## 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) ``` | Property | Type | Description | | - | - | - | | `conversations` | `[Conversation]` | The conversations loaded so far, most recently active first. | | `hasMore` | `Bool` | There are more pages to load. | | `error` | `QwryError?` | 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) } } ``` ## Related > [card] Streaming | /docs/ios-sdk/streaming | The send and handler API underneath. > [card] Client-Side Tools | /docs/ios-sdk/client-side-tools | What fills in the tool parts. > [card] Conversations & History | /docs/ios-sdk/conversations | The paging behind these classes. > [card] Error Handling | /docs/ios-sdk/error-handling | Turning error into a message your users understand.