← All courses ← Course home

Lesson 02 of 05

Stream tokens in the UI

Call streamResponse, then paint each partial string. Waiting for the full answer makes a live model look idle.

Agent brief (llms.md)

Environment setup

Xcode 27. iOS 27 or macOS 27. Add Foundation Models. Confirm streamResponse and the partial property name in the installed SDK.

Create a LanguageModelSession and stream the reply. The framework yields snapshots of the text so far. Update the screen on each snapshot.

APILanguageModelSession
APILanguageModelSession
CallstreamResponse
APILanguageModelSession
CallstreamResponse
UIPartial text
import FoundationModels

let session = LanguageModelSession()
let stream = session.streamResponse {
    "Write a two-sentence packing list for a day hike."
}

var visible = ""
for try await partial in stream {
    visible = partial.content
    // Bind `visible` to a SwiftUI Text view.
}

That sketch follows the public streamResponse path. Confirm the partial property name in the Xcode 27 SDK. Some builds expose content on the snapshot. Do not invent a second streaming API.

Show a typing cursor or a quiet status until the first token. Then replace it with the growing text. Do not block the main actor on the whole stream. The async sequence is the wait.

If you need structured output, Apple also documents streamResponse overloads that take a generable type or a schema. The clock work in the next lesson is the same: start before the call, mark the first yield, mark the last yield.

Keep instruction text in a registry, not in the view. Version prompts like product copy shows how.

Rule. Paint partial text. Do not wait for the last token to show the first word.

Next, put numbers on that stream.

Key concepts

  • Create a LanguageModelSession, call streamResponse, and bind partial text to SwiftUI.
  • The framework yields snapshots. Update the UI on each yield.
  • Confirm the partial-text property name in the Xcode 27 SDK.
  • Show a typing status until the first token, then growing text.

Takeaways

  • Paint partial text. Do not wait for the last token to show the first word.
  • Do not block the main actor on the whole stream.
  • Keep instruction text in a registry, not the view.