Project 11: AI Chatbot App with Streaming Replies

iOS App Development with Swift and SwiftUI: 13 Projects · More Real-World iOS Projects · 16 min read · Updated

A stream of growing text

  1. The user's message is saved and the recent history is prepared.
  2. The service returns an AsyncThrowingStream of the growing reply.
  3. Each value replaces the streaming text on screen.
  4. When it ends, or the user presses Stop, the text is saved as a message.

AI chat is now an ordinary app feature. The user types a question and the answer appears word by word. Building the screen is mostly about state: a list of finished messages plus one message still being written. Building it safely is about design: the AI key must stay on a server, the history sent must be limited, and the user must be able to stop a long answer.

So you can build and test everything without a key or server, the app uses two classes behind one protocol. FakeAIService makes up an answer slowly. ServerAIService calls your own backend. You start with the fake one and switch when your server is ready. Never put a secret AI key inside an app: anyone can extract it, and you would pay for their use.

Concepts in this project

  • Protocol with two implementations: AIService.reply(to:) returns an AsyncThrowingStream<String, Error> that yields the growing text.
  • Streaming state: finished messages live in messages, and the partial reply lives in streaming. It is saved only when complete or stopped.
  • Cancellation: the Stop button cancels the task. The stream's onTermination cancels the work behind it.
  • History window: only recent messages are sent, because the model has no memory and long requests cost more.
  • URLSession.bytes: reads a response as it arrives, so you can show text before the reply is finished.
  • Honest interface: a notice tells users that AI answers can be wrong.

Create the project

  1. In Xcode choose File > New > Project > iOS > App. Set Interface to SwiftUI, Language to Swift, and Testing System to Swift Testing. Set the minimum deployment to iOS 17, because the code uses @Observable. Name the product AIChat.
  2. Delete the default ContentView.swift and the default @main file, then add the files below.
AIChat/
  AIChatApp.swift     @main
  ChatMessage.swift   model + history window
  AIService.swift     protocol, FakeAIService, ServerAIService
  ChatViewModel.swift send, stop, streaming, saved history
  ChatScreen.swift    messages, input, Stop button
AIChatTests/
  AIChatTests.swift

The code

`ChatMessage.swift`

import Foundation

struct ChatMessage: Identifiable, Codable, Equatable {
    enum Role: String, Codable {
        case user
        case assistant
    }

    var id = UUID()
    let role: Role
    var text: String
}

enum History {
    // The model has no memory, so each request carries the conversation again.
    // Sending only the latest messages keeps requests small and cheap.
    static func recent(_ messages: [ChatMessage], limit: Int = 12) -> [ChatMessage] {
        Array(messages.suffix(limit))
    }
}

`AIService.swift`

import Foundation

protocol AIService {
    // Streams the growing reply. Each value is the whole text so far.
    func reply(to history: [ChatMessage]) -> AsyncThrowingStream<String, Error>
}

// Makes up an answer word by word, so you can build and test the whole app
// with no key, no server and no cost.
struct FakeAIService: AIService {
    func reply(to history: [ChatMessage]) -> AsyncThrowingStream<String, Error> {
        AsyncThrowingStream { continuation in
            let task = Task {
                let question = history.last?.text ?? ""
                let words = "You asked: \(question). This is a made-up answer. Connect the app to your own server to get real AI replies.".split(separator: " ")
                var text = ""
                for word in words {
                    if Task.isCancelled { break }
                    try? await Task.sleep(for: .milliseconds(120))
                    text += (text.isEmpty ? "" : " ") + word
                    continuation.yield(text)
                }
                continuation.finish()
            }
            continuation.onTermination = { _ in task.cancel() }
        }
    }
}

// Talks to YOUR server. The secret AI key lives on that server, never in this app.
// Contract: POST {"messages":[{"role":"user","text":"..."}]} and the server streams back plain text.
struct ServerAIService: AIService {
    let endpoint: URL

    func reply(to history: [ChatMessage]) -> AsyncThrowingStream<String, Error> {
        AsyncThrowingStream { continuation in
            let task = Task {
                do {
                    var request = URLRequest(url: endpoint)
                    request.httpMethod = "POST"
                    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
                    request.httpBody = try JSONEncoder().encode(["messages": History.recent(history)])

                    let (bytes, response) = try await URLSession.shared.bytes(for: request)
                    if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {
                        throw URLError(.badServerResponse)
                    }
                    var text = ""
                    for try await character in bytes.characters {
                        text.append(character)
                        continuation.yield(text)
                    }
                    continuation.finish()
                } catch {
                    continuation.finish(throwing: error)
                }
            }
            continuation.onTermination = { _ in task.cancel() }
        }
    }
}

`ChatViewModel.swift`

import Foundation
import Observation

@Observable
@MainActor
final class ChatViewModel {
    private(set) var messages: [ChatMessage]
    private(set) var streaming: String?
    private(set) var errorText: String?
    private let service: AIService
    private let defaults: UserDefaults
    private var job: Task<Void, Never>?

    init(service: AIService, defaults: UserDefaults = .standard) {
        self.service = service
        self.defaults = defaults
        if let data = defaults.data(forKey: "chat.v1"),
           let saved = try? JSONDecoder().decode([ChatMessage].self, from: data) {
            messages = saved
        } else {
            messages = []
        }
    }

    var isReplying: Bool { job != nil }

    func send(_ text: String) {
        let clean = text.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !clean.isEmpty, !isReplying else { return }
        errorText = nil
        messages.append(ChatMessage(role: .user, text: clean))
        save()
        streaming = ""

        let history = History.recent(messages)
        job = Task {
            var latest = ""
            do {
                for try await partial in service.reply(to: history) {
                    latest = partial
                    streaming = partial
                }
            } catch is CancellationError {
                // The user pressed Stop. Keep what we have.
            } catch {
                errorText = "Something went wrong. Please try again."
            }
            finish(with: latest)
        }
    }

    func stop() {
        job?.cancel()
    }

    func clear() {
        stop()
        messages = []
        save()
    }

    private func finish(with text: String) {
        if !text.isEmpty {
            messages.append(ChatMessage(role: .assistant, text: text))
            save()
        }
        streaming = nil
        job = nil
    }

    private func save() {
        if let data = try? JSONEncoder().encode(messages) {
            defaults.set(data, forKey: "chat.v1")
        }
    }
}

`ChatScreen.swift`

import SwiftUI

struct ChatScreen: View {
    @State private var model: ChatViewModel
    @State private var input = ""

    init(service: AIService) {
        _model = State(initialValue: ChatViewModel(service: service))
    }

    var body: some View {
        NavigationStack {
            VStack(spacing: 0) {
                Text("AI answers can be wrong. Check important facts.")
                    .font(.caption)
                    .foregroundStyle(.secondary)
                    .padding(.vertical, 4)

                ScrollViewReader { proxy in
                    ScrollView {
                        LazyVStack(alignment: .leading, spacing: 10) {
                            ForEach(model.messages) { message in
                                bubble(message.text, mine: message.role == .user)
                                    .id(message.id)
                            }
                            if let live = model.streaming {
                                bubble(live.isEmpty ? "..." : live + " ▌", mine: false)
                                    .id("live")
                            }
                            if let error = model.errorText {
                                Text(error).foregroundStyle(.red).font(.callout)
                            }
                        }
                        .padding()
                    }
                    .onChange(of: model.messages.count) { _, _ in
                        if let last = model.messages.last { proxy.scrollTo(last.id, anchor: .bottom) }
                    }
                    .onChange(of: model.streaming) { _, _ in
                        proxy.scrollTo("live", anchor: .bottom)
                    }
                }

                HStack {
                    TextField("Ask something", text: $input, axis: .vertical)
                        .textFieldStyle(.roundedBorder)
                        .lineLimit(1...4)
                    if model.isReplying {
                        Button("Stop") { model.stop() }
                    } else {
                        Button("Send") {
                            model.send(input)
                            input = ""
                        }
                        .disabled(input.trimmingCharacters(in: .whitespaces).isEmpty)
                    }
                }
                .padding()
            }
            .navigationTitle("Assistant")
            .toolbar {
                Button("Clear", role: .destructive) { model.clear() }
            }
        }
    }

    private func bubble(_ text: String, mine: Bool) -> some View {
        Text(text)
            .padding(10)
            .background(mine ? Color.blue : Color(.secondarySystemBackground),
                        in: RoundedRectangle(cornerRadius: 14))
            .foregroundStyle(mine ? Color.white : Color.primary)
            .frame(maxWidth: .infinity, alignment: mine ? .trailing : .leading)
    }
}

`AIChatApp.swift`

import SwiftUI

@main
struct AIChatApp: App {
    var body: some Scene {
        WindowGroup {
            // Start with the fake service. Switch to ServerAIService(endpoint: ...)
            // when your own server is ready.
            ChatScreen(service: FakeAIService())
        }
    }
}

`AIChatTests.swift (in the tests target)`

import Testing
import Foundation
@testable import AIChat

@MainActor
struct AIChatTests {
    private func defaults() -> UserDefaults {
        UserDefaults(suiteName: UUID().uuidString)!
    }

    @Test func historyKeepsOnlyTheLatestMessages() {
        let many = (1...30).map { ChatMessage(role: .user, text: "m\($0)") }
        let recent = History.recent(many, limit: 5)
        #expect(recent.count == 5)
        #expect(recent.first?.text == "m26")
    }

    @Test func fakeServiceStreamsAGrowingText() async throws {
        var parts: [String] = []
        for try await partial in FakeAIService().reply(to: [ChatMessage(role: .user, text: "Hi")]) {
            parts.append(partial)
        }
        #expect(parts.count > 3)
        #expect(parts[1].hasPrefix(parts[0]))
    }

    @Test func replyIsSavedWhenFinished() async throws {
        let model = ChatViewModel(service: FakeAIService(), defaults: defaults())
        model.send("What is Swift?")
        while model.isReplying { try await Task.sleep(for: .milliseconds(50)) }
        #expect(model.messages.count == 2)
        #expect(model.messages.last?.role == .assistant)
    }

    @Test func emptyMessageIsIgnored() {
        let model = ChatViewModel(service: FakeAIService(), defaults: defaults())
        model.send("   ")
        #expect(model.messages.isEmpty)
    }
}

Walkthrough

AsyncThrowingStream is the bridge between a producer that pushes values and a consumer that loops with for try await. In FakeAIService, a task splits the answer into words and yields the text so far every 120 milliseconds. continuation.onTermination cancels that task if the consumer stops listening, so no work continues in the background.

ServerAIService does the same with real data. It encodes the recent history as JSON, posts it and reads the answer with URLSession.bytes. Each character that arrives is appended and yielded. The contract with your server is simple: it receives the messages and streams back plain text. The secret key, the choice of model, usage limits and a system prompt all belong on that server.

ChatViewModel.send trims the text, ignores empty input and ignores a second send while a reply is running. It saves the user's message, sets streaming to an empty string and starts a task that loops over the stream. Each partial value replaces streaming, so the screen shows the growing answer with a cursor mark. When the loop ends, finish stores the whole answer as an assistant message, saves, and clears the streaming state.

Stop works through cancellation. stop cancels the task, the loop ends, and finish stores whatever text was received so far. The user keeps the partial answer instead of losing it. An error shows a short message, never the raw error text, because raw errors can leak details.

In the view, a ScrollViewReader keeps the newest text in view. The bottom bar swaps the Send button for Stop while a reply is running. The tests check that history is limited, that the fake stream grows, that a finished reply is saved and that empty messages are ignored, all without a network.

How it works

  • send stores the user message and starts a task that reads the reply stream.
  • Each emitted text updates streaming, so the screen shows the answer as it grows.
  • When the stream ends or Stop is pressed, the text is saved as an assistant message.
  • Messages are encoded to JSON and saved, so the conversation survives closing the app.

Expected output

The screen shows the title Assistant, the notice "AI answers can be wrong. Check important facts." and an input box. Type "What is Swift?" and press Send: your message appears on the right in blue. An answer then builds up on the left word by word, ending with "Connect the app to your own server to get real AI replies." while the button shows Stop. Press Stop in the middle: the partial text stays. Close and reopen the app: the conversation is still there. Clear removes it. All four tests pass.

Your task

  1. Build the app with the fake service and chat with it.
  2. Write the server contract for your own backend and test it with a tool such as curl.
  3. Add a system prompt on the server, not in the app.
  4. Add a daily message limit on the server and show a friendly message when it is reached.

How to check it worked

  • No AI key exists in the app or the repository.
  • Stop keeps the partial answer.
  • Only recent messages are sent.

Next, try the same idea on another platform with the Android Development with Kotlin course, or go deeper on iOS with the Advanced iOS Development course.

Frequently asked questions

Why not call the AI service directly from the app?

The secret key would be inside the app, where anyone can extract it. A server also lets you add limits, logging and safety rules.

Why send only recent messages?

The model has no memory, so you send context every time. Long histories cost more and can exceed limits, so send a recent window or a summary.

What does onTermination do?

It runs when the stream ends or the consumer stops listening, so you can cancel the producer task and avoid wasted work.