Build a chat screen with SwiftUI
Build a streaming chat screen in SwiftUI with an ObservableObject view model that wraps OctoClient, plus a send button and a stop action.
Working draft. These docs are illustrative: names, endpoints and examples describe the intended behaviour and can change before launch.
This page builds a small chat screen: a list of messages, a text field and a send button, with the answer appearing as it streams. The example targets iOS 16, so it uses ObservableObject and @Published instead of the Observation framework.
The view model
Keep the client and the stream in a view model. The model holds one ChatLine per bubble, where ChatLine is a small Identifiable struct with an id, an isUser flag and a text string.
@MainActor
final class ChatViewModel: ObservableObject {
@Published var lines: [ChatLine] = []
@Published var isStreaming = false
@Published var failure: String?
private let octo: OctoClient
private var conversationId: String?, task: Task<Void, Never>?
init(octo: OctoClient) { self.octo = octo }
func send(_ text: String) {
lines += [ChatLine(isUser: true, text: text), ChatLine(isUser: false, text: "")]
isStreaming = true
task = Task {
do {
for try await event in octo.streamChat(text: text, conversationId: conversationId) {
switch event {
case .messageDelta(let piece): lines[lines.count - 1].text += piece
case .messageDone(let message, let id):
lines[lines.count - 1].text = message.content; conversationId = id
case .toolCall: break
case .error(let error): failure = error.localizedDescription
}
}
} catch { failure = error.localizedDescription }
isStreaming = false
}
}
func stop() { task?.cancel() }
}
The Task inherits the main actor from the class, so updating lines inside the loop is safe. The first reply stores conversationId, and later messages continue the same thread.
The view
struct ChatView: View {
@StateObject private var model: ChatViewModel
@State private var draft = ""
init(octo: OctoClient) {
_model = StateObject(wrappedValue: ChatViewModel(octo: octo))
}
var body: some View {
VStack {
List(model.lines) { line in
Text(line.text)
.frame(maxWidth: .infinity, alignment: line.isUser ? .trailing : .leading)
}
HStack {
TextField("Message", text: $draft)
Button(model.isStreaming ? "Stop" : "Send") {
if model.isStreaming { model.stop() } else { model.send(draft); draft = "" }
}
}
.padding()
}
}
}
Run the screen and send a message. You should see an empty bubble appear, fill with text piece by piece, and the button return to Send when the answer is complete.
Show errors and handoffs
- Bind
model.failureto an alert or a banner. The text comes fromlocalizedDescriptionof an OctoError. - Add a retry button that calls
sendagain with the last user line. - Load the conversation
statusand show a line when it ishandoff, as described in Conversations.
Tip: Create the
OctoClientonce and pass it into the view. Creating it inside the view body gives you a new client on every redraw.