widget_chat is live on pub.dev: drop-in AI chat for Flutter, FlutterFlow, iOS, Android, React & Web. Start free →

← Back to Blog
Add an AI Support Chatbot to a SwiftUI App: Two Routes

Add an AI Support Chatbot to a SwiftUI App: Two Routes

swiftuiiosai chatbotswift package managerstreamingcustomer support

Search for a swiftui ai chatbot and most results are vendor docs that start with an AppDelegate, a UIKit wrapper or a whole chat platform. A native SwiftUI app has two cleaner routes: build the chat screen yourself with URLSession streaming against your own backend, or add a native chat view through Swift Package Manager.

This post walks through both, with code, and lists what each one leaves you to maintain. The second route in one line: Widget-Chat ships a native SwiftUI SDK, so WidgetChatView(secretKey:userID:) is the whole chat screen on iOS 17+. The hand-built route comes first, because it is what the SDK replaces.

What a chat request looks like

User types a questionSwiftUI viewPOST api.example.com/chat/streamYour backend adds the provider keyModel provider
Model streams tokensYour backend relays linesURLSession.bytesMessage stateBubble grows on screen

The provider key never ships in the app. An iOS binary can be unpacked, and a key inside it is a key anyone can spend. The app talks only to your own endpoint, which checks who the user is and calls the model.

Route 1: a hand-built SwiftUI chat view with streaming

Message state and the stream

iOS 17 added the Observation framework, so the model is a plain class marked @Observable. URLSession.bytes(for:) returns as soon as the response headers arrive and hands over the body as an AsyncSequence. Calling .lines on it gives you text lines as they come in.

import Foundation
import Observation

struct ChatMessage: Identifiable {
    enum Role { case user, assistant }
    let id = UUID()
    let role: Role
    var text: String
}

private struct Chunk: Decodable { let delta: String }

@MainActor
@Observable
final class ChatModel {
    var messages: [ChatMessage] = []
    var isStreaming = false
    var errorText: String?
    private var task: Task<Void, Never>?

    func send(_ text: String, sessionToken: String) {
        guard !isStreaming else { return }
        messages.append(ChatMessage(role: .user, text: text))
        messages.append(ChatMessage(role: .assistant, text: ""))
        let index = messages.count - 1
        isStreaming = true

        task = Task {
            defer { isStreaming = false }
            do {
                var request = URLRequest(url: URL(string: "https://api.example.com/chat/stream")!)
                request.httpMethod = "POST"
                request.setValue("application/json", forHTTPHeaderField: "Content-Type")
                request.setValue("Bearer \(sessionToken)", forHTTPHeaderField: "Authorization")
                request.httpBody = try JSONEncoder().encode(["message": text])

                let (bytes, response) = try await URLSession.shared.bytes(for: request)
                guard (response as? HTTPURLResponse)?.statusCode == 200 else {
                    throw URLError(.badServerResponse)
                }

                for try await line in bytes.lines {
                    guard line.hasPrefix("data: ") else { continue }
                    let payload = line.dropFirst(6)
                    if payload == "[DONE]" { break }
                    let chunk = try JSONDecoder().decode(Chunk.self, from: Data(payload.utf8))
                    messages[index].text += chunk.delta
                }
            } catch {
                if !Task.isCancelled { errorText = "Could not reach support. Try again." }
            }
        }
    }

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

The wire format here is your own choice: each line is data: {"delta":"..."} and the stream ends with data: [DONE]. sessionToken is your app's own user session, never the model provider's key.

The screen

import SwiftUI

struct SupportChatView: View {
    @State private var model = ChatModel()
    @State private var draft = ""
    let sessionToken: String

    var body: some View {
        VStack(spacing: 0) {
            ScrollView {
                LazyVStack(spacing: 12) {
                    ForEach(model.messages) { message in
                        Text(message.text)
                            .padding(10)
                            .background(.gray.opacity(0.12), in: .rect(cornerRadius: 12))
                            .frame(maxWidth: .infinity,
                                   alignment: message.role == .user ? .trailing : .leading)
                    }
                }
                .padding()
            }
            .defaultScrollAnchor(.bottom)

            HStack {
                TextField("Ask a question", text: $draft, axis: .vertical)
                    .textFieldStyle(.roundedBorder)
                Button("Send") {
                    model.send(draft, sessionToken: sessionToken)
                    draft = ""
                }
                .disabled(draft.trimmingCharacters(in: .whitespaces).isEmpty || model.isStreaming)
            }
            .padding()
        }
    }
}

defaultScrollAnchor(.bottom) (iOS 17+) starts the list at the newest message. That is roughly 90 lines of Swift and it works in a demo.

What the demo leaves out

The code above is the easy tenth. A swiftui customer support chat that real users open needs more:

  • History. Messages live in memory, so they vanish when the view goes away. You need a store on your backend, an endpoint to page through it, and scroll handling that stays put when older messages load in above.
  • Markdown. Models answer in markdown. Text renders inline styles from an AttributedString, but lists, tables and code blocks are yours to lay out, and they arrive half-finished while the stream is running.
  • Failure. Retry, a stop button, a dropped connection mid-answer, a rate limit from the provider.
  • The backend. An authenticated streaming endpoint, the prompt, retrieval over your help content, and the provider's API changes over time.
  • Everything users expect next: image attachments, product cards, dark mode, translated UI.

Route 2: a native SwiftUI chat view through Swift Package Manager

The Widget-Chat iOS SDK is a Swift package that renders the chat natively in SwiftUI, with no webview. It needs iOS 17+ and Swift 5.9+.

  1. Create a projectSign up free at app.widget-chat.com, add your help content and copy the project key.
  2. Add the packageIn Xcode choose File, Add Package Dependencies and paste https://github.com/tajaouart/WidgetChat-iOS.
  3. Import itAdd import WidgetChat to the file that shows your support screen.
  4. Place the viewPut WidgetChatView(secretKey:userID:) in a sheet, a tab or a navigation destination.
  5. Run itAsk a question your content answers and check the reply.

If you manage dependencies in Package.swift:

.package(url: "https://github.com/tajaouart/WidgetChat-iOS", from: "0.0.1")

Then the screen is one view:

import SwiftUI
import WidgetChat

struct SupportView: View {
    let user: User

    var body: some View {
        WidgetChatView(
            secretKey: "YOUR_PROJECT_KEY",
            userID: user.id
        )
    }
}

There is no AppDelegate setup and no UIKit wrapper. The project key identifies your project and is meant to ship in the app. The model provider key stays on the server side, and there is no chat backend for you to build or host. The assistant answers from your own content, and its theme, languages and tools are set in a no-code dashboard.

The view comes with markdown, rich messages (image cards, carousels, product lists, button groups, colour swatches), image attachments, message history, light and dark themes, and replies in 100+ languages with a locale picker.

Hand-built chat

  • A streaming endpoint to write, secure and host
  • Your own parser for the stream, with its edge cases
  • Message state, scroll and history paging by hand
  • Markdown, cards and attachments built one by one
  • Prompt and content changes need a deploy

WidgetChatView through SPM

  • No chat backend to build or host
  • One SwiftUI view, rendered natively
  • History, themes and rich messages included
  • Image attachments included
  • Content, theme and tools edited in a dashboard
Same goal, in-app AI chat on iOS in Swift. The difference is who maintains the parts.

What each route leaves you to maintain

Part Hand-built Widget-Chat iOS SDK
Streaming endpoint and provider key You Not needed
Stream parsing and retries You Included
Chat UI, scroll, keyboard You Included
History and pagination You, client and server Included
Markdown and rich messages You Included
Answers from your help content You (retrieval pipeline) Dashboard
Verified user identity Your own auth HMAC signature, signed on your backend
Full control of every pixel and the wire format Yes No, themed from the dashboard
Live voice You Not on native iOS

The hand-built route is the right call when the chat is your product, when you need a layout no SDK will give you, or when you already run the model backend for other features. For support chat inside an app whose product is something else, the maintenance column is hard to justify.

One thing stays on your side either way: if users must not be able to read each other's conversations, sign the user ID on your backend. The SDK accepts the signature through its optional userIdSignature parameter. The idea is the same on every platform, and the HMAC identity post explains the signing step.

Running a Flutter app too? Same project, same dashboard

Many teams with a native SwiftUI app also ship a Flutter or FlutterFlow app. The iOS SDK uses the same backend and dashboard as the Flutter package, so one project serves both. In Flutter, add the package with flutter pub add widget_chat and place the widget:

ChatWidget(
  configuration: BotConfiguration(
    projectSecretKey: 'your-project-secret-key',
    userID: 'user-123',
  ),
)

The Flutter package is also where live voice is available today. FlutterFlow teams can follow the FlutterFlow guide, which adds the package as a custom dependency.

  • Provider key stays off the device on both routes
  • Hand-built: your own endpoint, parser, history and UI
  • SDK: one Swift package, one view, iOS 17+
  • No live voice on native iOS yet
  • Sign the user ID with HMAC when conversations are private

The free plan needs no credit card. Create a Widget-Chat project, copy the project key, and the SwiftUI view above is your support screen.

The Widget-Chat iOS SDK repository, installed through Swift Package Manager

Apple's documentation for URLSession.AsyncBytes, the type behind streaming with bytes(for:)

Put an AI chat widget on your site or app

Widget-Chat answers your visitors from your own content. Set it up in a no-code dashboard, then embed it with one snippet on the web, or one package in Flutter and FlutterFlow.

Free plan, no credit card.

Widget-Chat

About the author

Widget-Chat is built by a small team of Flutter developers. We write about the problems we hit while shipping AI chat in production apps.