How to Stream AI-Generated SwiftUI Screens from Your Backend Using Uzori
By the end of this tutorial you’ll have a working path from a plain LLM answer to a streaming, server‑driven SwiftUI screen rendered via Uzori inside your iOS…

By the end of this tutorial you’ll have a working path from a plain LLM answer to a streaming, server‑driven SwiftUI screen rendered via Uzori inside your iOS app.
You’ll see how to:
- Call an LLM from your backend
- Turn its response into structured JSON that describes a screen
- Validate that JSON with a strict schema
- Stream updates over SSE (or similar)
- Let Uzori render the result as native SwiftUI in real time
This is a concrete example of server-driven UI for iOS, where AI composes the interface but your backend stays in control.
Prerequisites
Before step 1, you should have:
- An iOS app using SwiftUI (Xcode 15+ recommended)
- Uzori iOS SDK installed (via Swift Package Manager or equivalent)
- Backend service capable of:
- Calling an LLM (OpenAI, Anthropic, etc.)
- Exposing HTTP endpoints to your app
- Sending streaming responses (Server-Sent Events or chunked HTTP)
- A JSON Schema validator on the backend
- For example Ajv (TypeScript) or
jsonschema(Python)
- For example Ajv (TypeScript) or
- An API description for your backend
- OpenAPI is ideal if you want to expand into AI-orchestrated flows later
If you want a broader architectural overview of server-driven UI on iOS, see this in-depth guide: Server-driven UI on iOS: turn AI answers into native SwiftUI in real time.
1. Start from a plain LLM answer
Goal: Confirm your backend can call an LLM and get a basic text answer from a user prompt.
Example scenario
User query:
"Find me a roaming protection plan for my Spain trip."
Naive LLM answer:
You should contact your carrier and ask about travel add-ons.
Consider disabling roaming and checking your plan limits before you leave.
That’s helpful, but it’s just text. Your app still has to build UI manually.
Backend example (TypeScript / Node)
import fetch from "node-fetch";
async function callLLMPlainAnswer(prompt: string): Promise<string> {
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`
},
body: JSON.stringify({
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: prompt }
]
})
});
const json = await res.json();
return json.choices[0].message.content as string;
}
// Quick smoke test
callLLMPlainAnswer("Find me a roaming protection plan for Spain.")
.then(console.log)
.catch(console.error);
Common failure at this step
- Problem: LLM call fails with 401/403.
- Fix: Double-check API key configuration and ensure your backend can reach the LLM provider.
Once this works, you’re ready to ask the model for structured UI, not prose.
2. Design a server-approved UI schema for SwiftUI screens
Goal: Define a constrained JSON schema that describes the screens you’re willing to render.
According to JSON Schema, you can use type, enum, and additionalProperties: false to strictly control structure and data types. This is critical because OWASP’s guidance on prompt injection emphasizes treating LLM output as untrusted.
Minimal screen schema example
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["screenType", "title", "sections"],
"additionalProperties": false,
"properties": {
"screenType": {
"type": "string",
"enum": ["comparison", "wizard", "detail", "list"]
},
"title": { "type": "string", "minLength": 1 },
"subtitle": { "type": "string" },
"sections": {
"type": "array",
"minItems": 1,
"items": { "$ref": "#/$defs/section" }
}
},
"$defs": {
"section": {
"type": "object",
"required": ["type"],
"additionalProperties": false,
"properties": {
"type": {
"type": "string",
"enum": ["text", "card", "cta", "table", "image"]
},
"title": { "type": "string" },
"body": { "type": "string" },
"items": {
"type": "array",
"items": { "$ref": "#/$defs/item" }
}
}
},
"item": {
"type": "object",
"required": ["label", "value"],
"additionalProperties": false,
"properties": {
"label": { "type": "string" },
"value": { "type": "string" }
}
}
}
}
Common failure at this step
- Problem: Schema is too loose (no enums,
additionalProperties: true). - Risk: LLM can emit unexpected fields or structures that break your client.
- Fix: Tighten the schema with
enum,required, andadditionalProperties: falseso every possible screen is explicitly defined.
3. Prompt the LLM for structured UI JSON instead of prose
Goal: Make the model act as a UI planner. It should output JSON matching your schema and nothing else.
Prompt example
You are a UI planner for a SwiftUI app.
Return ONLY valid JSON matching the schema.
Do not include markdown.
Do not include explanations.
Do not invent unsupported components.
Use only these screen types: comparison, wizard, detail, list.
Use only these section types: text, card, cta, table, image.
User goal:
Find me a roaming protection plan for Spain.
Backend call for structured UI (TypeScript)
async function callLLMForUIScreen(prompt: string): Promise<string> {
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`
},
body: JSON.stringify({
model: "gpt-4o",
response_format: { type: "json_object" },
messages: [
{
role: "system",
content:
"You are a UI planner. Return ONLY JSON that matches the UI schema."
},
{ role: "user", content: prompt }
]
})
});
const json = await res.json();
return json.choices[0].message.content as string;
}
Common failure at this step
- Problem: Model returns natural language or JSON wrapped in backticks.
- Fix:
- Use
response_format: { type: "json_object" }where available. - Hard fail if the response contains non-JSON characters (e.g., backticks, `````,
"```json").
- Use
4. Validate AI-generated UI with JSON Schema and business rules
Goal: Treat the LLM as an untrusted proposer. Your backend validates and only then forwards the UI to the client.
OWASP’s prompt injection guidance and NIST’s GenAI risk management work both emphasize strong validation, TEVV (testing, evaluation, verification, and validation), and layered defenses.
Validation pipeline (TypeScript with Ajv)
import Ajv from "ajv";
import uiSchema from "./ui-schema.json";
const ajv = new Ajv({ allErrors: true, strict: true });
const validate = ajv.compile(uiSchema);
export interface UIScreen {
screenType: "comparison" | "wizard" | "detail" | "list";
title: string;
subtitle?: string;
sections: UIScreenSection[];
}
export interface UIScreenSection {
type: "text" | "card" | "cta" | "table" | "image";
title?: string;
body?: string;
items?: { label: string; value: string }[];
}
export async function buildValidatedScreen(
userPrompt: string
): Promise<UIScreen> {
const raw = await callLLMForUIScreen(userPrompt);
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch (e) {
throw new Error("LLM returned invalid JSON");
}
const ok = validate(parsed);
if (!ok) {
throw new Error(`Schema validation failed: ${JSON.stringify(validate.errors)}`);
}
const screen = parsed as UIScreen;
// Business rule validation examples
if (screen.screenType === "wizard" && screen.sections.length > 5) {
throw new Error("Wizard screens may not exceed 5 sections");
}
if (screen.title.length > 80) {
throw new Error("Title too long");
}
// Safety & brand constraints
screen.sections.forEach((section) => {
if (section.body && /<script|javascript:/i.test(section.body)) {
throw new Error("Potentially unsafe content in section body");
}
});
return screen;
}
Common failure at this step
- Problem: You only validate the schema, not business logic.
- Risk: Screens may be technically valid but unusable (too many sections, bad copy, missing CTAs).
- Fix: Add business rules for:
- Section count and nesting depth
- Text length limits
- Required disclaimers for certain flows (e.g., pricing, legal)
5. Stream validated UI from your backend (SSE example)
Goal: Stream AI-generated SwiftUI screen updates to the client as they’re built, instead of waiting for a full response.
Uzori’s architecture pattern is: AI composes UI, your backend validates, and then the UI is streamed live into the running app.
5.1 Design streaming events
Define a simple event protocol for your server-driven UI:
screen.start– announce a new screenscreen.section– add a sectionscreen.complete– mark completion
Example event stream (text)
event: screen.start
data: {"screenId":"roaming-123","screenType":"comparison","title":"Spain roaming options"}
event: screen.section
data: {"type":"card","title":"Day Pass","body":"5 GB / day for $10"}
event: screen.section
data: {"type":"card","title":"Weekly Pack","body":"20 GB / week for $40"}
event: screen.complete
data: {"screenId":"roaming-123"}
5.2 Implement SSE endpoint (Node / Express)
import express from "express";
import { buildValidatedScreen } from "./ui-builder";
const app = express();
app.get("/api/ai-screen", async (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
const userPrompt = (req.query.q as string) || "";
try {
const screen = await buildValidatedScreen(userPrompt);
const screenId = `screen-${Date.now()}`;
// Start event
res.write(
`event: screen.start\n` +
`data: ${JSON.stringify({
screenId,
screenType: screen.screenType,
title: screen.title,
subtitle: screen.subtitle ?? null
})}\n\n`
);
// Stream each section
for (const section of screen.sections) {
res.write(
`event: screen.section\n` +
`data: ${JSON.stringify({ screenId, section })}\n\n`
);
}
// Complete event
res.write(
`event: screen.complete\n` +
`data: ${JSON.stringify({ screenId })}\n\n`
);
res.end();
} catch (err) {
res.write(
`event: error\n` +
`data: ${JSON.stringify({ message: (err as Error).message })}\n\n`
);
res.end();
}
});
app.listen(3000, () => {
console.log("Backend listening on http://localhost:3000");
});
Common failure at this step
- Problem: Response buffers and only flushes at the end.
- Fix:
- Make sure you’re not behind a proxy that buffers SSE.
- Avoid writing large chunks before flushing; write each event as a separate
res.write().
6. Integrate Uzori’s SwiftUI SDK in your iOS app
Goal: Add Uzori’s single-screen integration so your app can receive and render streaming, server-driven SwiftUI from your backend.
Uzori is designed as a drop-in SwiftUI screen. The SDK connects to your backend, pulls streamed UI descriptions, and renders them as native SwiftUI views.
6.1 Add Uzori to your project
- In Xcode, go to File → Add Packages…
- Enter the Uzori package URL (from your Uzori account docs).
- Add the package to your app target.
6.2 Create a host view for Uzori
import SwiftUI
import Uzori
struct AIConciergeScreen: View {
var body: some View {
UzoriScreen(
server: .init(url: URL(string: "https://api.yourapp.com")!),
configuration: .configuration,
credentials: .live(
apiKey: "YOUR_UZORI_KEY",
userId: "user-123"
)
)
}
}
Then embed it in your main navigation:
struct ContentView: View {
var body: some View {
NavigationStack {
AIConciergeScreen()
.navigationTitle("AI Assistant")
}
}
}
What Uzori does for you
- Connects to your backend with the credentials you provide
- Opens a streaming connection (e.g., SSE)
- Parses the server-driven UI JSON emitted by your backend
- Renders it as native SwiftUI views, not a web view
Common failure at this step
- Problem: Nothing appears on screen; just a blank view.
- Fix:
- Check the URL and path your
UzoriScreenis pointing to. - Verify the backend is returning SSE events and not a 404/500.
- Check the URL and path your
For a full Uzori iOS SDK reference and configuration options, see the docs on uzori.ai.
7. Map schema components to SwiftUI using Uzori
Goal: Ensure your server’s schema lines up with how Uzori composes SwiftUI screens.
Uzori consumes a constrained, server-driven schema and maps it to your app’s components. Conceptually, the mapping looks like:
screenType: "comparison"→ vertical list with comparison cardsscreenType: "wizard"→ multi-step flow with Next / Backsection.type: "card"→VStackwith title, body, and optional metadatasection.type: "cta"→Buttonbound to an action defined in your schema
Sample SwiftUI-style mental model
This is not code you write by hand, but it reflects what Uzori does internally:
@ViewBuilder
func renderSection(_ section: UIScreenSection) -> some View {
switch section.type {
case .text:
VStack(alignment: .leading, spacing: 8) {
if let title = section.title {
Text(title).font(.headline)
}
if let body = section.body {
Text(body).font(.body)
}
}
case .card:
VStack(alignment: .leading, spacing: 4) {
if let title = section.title {
Text(title).font(.headline)
}
if let body = section.body {
Text(body).font(.subheadline)
}
}
.padding()
.background(.ultraThinMaterial)
.clipShape(RoundedRectangle(cornerRadius: 12))
case .cta:
if let title = section.title {
Button(title) {
// Bound to a server-defined action
}
.buttonStyle(.borderedProminent)
}
case .table:
VStack(alignment: .leading) {
if let title = section.title {
Text(title).font(.headline)
}
if let items = section.items {
ForEach(items, id: \ .label) { item in
HStack {
Text(item.label)
Spacer()
Text(item.value)
}
}
}
}
case .image:
// Uzori can map to AsyncImage or a custom image component
EmptyView() // Placeholder for this example
}
}
Because your schema is constrained, Uzori can safely map each approved section type to a known SwiftUI component.
Common failure at this step
- Problem: LLM invents a new section type (e.g.,
"chart") that your client doesn’t know. - Fix:
- Ensure
section.typeis anenumin the schema. - Reject any unknown types during validation and log them for debugging.
- Ensure
8. Wire user input into the AI-driven screen
Goal: Close the loop: let users type queries, send them to your backend, and see AI-generated SwiftUI screens stream back in real time.
In a typical Uzori integration:
- The
UzoriScreenprovides an input field or uses your custom trigger - Each user query hits your backend endpoint (e.g.,
/api/ai-screen?q=...) - Backend:
- Calls the LLM with the prompt
- Validates the UI JSON
- Streams
screen.*events
- Uzori renders the streamed updates as SwiftUI
Pseudocode interaction flow
- User types:
"Plan my Spain roaming" - iOS app → Uzori → Backend:
GET /api/ai-screen?q=Plan+my+Spain+roaming - Backend builds and validates
UIScreen - SSE events ship down:
screen.startscreen.section(cards, text, CTAs)screen.complete
- Uzori composes SwiftUI views incrementally and updates the screen as events arrive.
Common failure at this step
- Problem: You treat the endpoint as request/response only, not streaming.
- Fix:
- Make sure your networking stack (and Uzori server config) is set up for streaming.
- Avoid terminating connections early or buffering entire responses on the server.
FAQ / Troubleshooting
1. How is this different from a normal chat UI in my iOS app?
With a traditional chat UI, the LLM returns text and your user has to mentally translate that into actions. With Uzori’s server-driven UI approach, the LLM returns a screen description (JSON), your backend validates it, and Uzori renders the result as operable SwiftUI: cards, lists, forms, CTAs, wizards.
2. Why do I need server-side validation for AI-generated UI?
OWASP classifies prompt injection and similar attacks as a major risk for LLM applications. NIST’s GenAI resources emphasize rigorous testing and validation. Treat LLM output as untrusted:
- Schema validation ensures structure and types are correct
- Business rules enforce UX and legal constraints
- Safety checks strip harmful or unsupported content
Without this layer, you risk UI breakage, inconsistent flows, or unsafe content.
3. Can I use GraphQL instead of REST/OpenAPI with Uzori?
Yes. Uzori works with your existing backend architecture. OpenAPI is convenient for describing REST APIs to the AI engine, but you can also:
- Use GraphQL schemas
- Wrap GraphQL calls behind REST endpoints that Uzori and the LLM see
The key is giving the AI engine structured, documented APIs it can call when orchestrating flows.
4. What about latency when streaming AI-generated SwiftUI screens?
Streaming helps hide model latency by:
- Rendering headers and skeleton sections first
- Filling in cards, tables, and CTAs as they arrive
On the backend side:
- Use low-latency LLM models when possible
- Stream tokens or partial UI chunks instead of waiting for full responses
On the client side:
- Let Uzori handle progressive rendering so users see a responsive interface.
5. How do I keep AI-generated UI on-brand?
Use your schema and validation hooks to encode brand constraints:
- Restricted set of components, spacing patterns, and layouts
- Text length limits and tone guidelines
- Only approved colors and styles (implemented in your SwiftUI components)
Because Uzori renders your SwiftUI components, the AI-driven screens inherit your design system automatically.
By following these steps, you’ve:
- Turned plain LLM answers into structured UI JSON
- Validated that JSON against a strict schema and business rules
- Streamed events from your backend over SSE
- Let Uzori render those events into native SwiftUI screens inside your iOS app
This is the foundation of an AI-native, server-driven UI architecture on iOS: the interface that builds itself while you stay in control of structure, safety, and brand.