Claude API Swift iOS App Integration Guide
Claude API Swift iOS App Integration
If you're building a Swift iOS app and want to add Claude for chat, summarization, or AI-assisted features, the core challenge isn't the Swift code — it's deciding where your API calls actually originate. Anthropic's API is designed to be called from a server, not from a mobile client, because shipping your API key inside an app binary exposes it to anyone who decompiles the bundle.
This article covers both pieces: the Swift networking code you need to talk to a Claude-compatible HTTPS API, and the architecture decision that keeps your credentials safe while your app ships to the App Store.
Why you can't call Claude directly from the app
Embedding sk-ant-... or any secret key as a string constant in your Swift source means it ships inside the .ipa file. Tools like strings, class-dump, or basic MITM proxying will extract it in minutes. Once exposed, that key can run up usage charges on your account with no rate limiting from your side.
The standard fix is a thin backend layer: your iOS app calls your own HTTPS endpoint, that endpoint holds the real credentials, and it forwards the request to Claude. This is also where SubToAPI fits — it turns your existing Claude access into an HTTPS API with its own application keys (sub_live_...), so you get a stable, revocable, per-app key to put in your mobile client instead of a raw provider secret. You can scope and rotate sub_live_ keys per app or per team member without touching your underlying Claude account.
Minimal Swift client with URLSession
Here's a basic async/await client for sending a message request from Swift:
import Foundation
struct ClaudeMessage: Codable {
let role: String
let content: String
}
struct ClaudeRequest: Codable {
let model: String
let max_tokens: Int
let messages: [ClaudeMessage]
}
struct ClaudeTextBlock: Codable {
let type: String
let text: String
}
struct ClaudeResponse: Codable {
let content: [ClaudeTextBlock]
}
func sendMessage(prompt: String) async throws -> String {
let url = URL(string: "https://api.subtoapi.app/v1/messages")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
let body = ClaudeRequest(
model: "claude-3-5-sonnet-20241022",
max_tokens: 1024,
messages: [ClaudeMessage(role: "user", content: prompt)]
)
request.httpBody = try JSONEncoder().encode(body)
let (data, _) = try await URLSession.shared.data(for: request)
let decoded = try JSONDecoder().decode(ClaudeResponse.self, from: data)
return decoded.content.first?.text ?? ""
}
Even with a proxy like SubToAPI standing between your app and Claude, the apiKey above should still not be a hardcoded secret in production builds — fetch it per-user from your own auth system, or at minimum store it in the Keychain rather than source code, and use short-lived or per-device keys where possible.
Streaming responses in SwiftUI
Chat interfaces feel sluggish if you wait for the full response before rendering anything. Claude supports server-sent events for streaming, and URLSession can consume them with bytes(for:):
func streamMessage(prompt: String, onToken: @escaping (String) -> Void) async throws {
var request = URLRequest(url: URL(string: "https://api.subtoapi.app/v1/messages")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
let body: [String: Any] = [
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"stream": true,
"messages": [["role": "user", "content": prompt]]
]
request.httpBody = try JSONSerialization.data(withJSONObject: body)
let (bytes, _) = try await URLSession.shared.bytes(for: request)
for try await line in bytes.lines {
guard line.hasPrefix("data: ") else { continue }
let payload = line.dropFirst(6)
if let data = payload.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let delta = json["delta"] as? [String: Any],
let text = delta["text"] as? String {
onToken(text)
}
}
}
Bind onToken to append characters to a @Published string in your view model, and SwiftUI will re-render the chat bubble as tokens arrive. For the exact event shapes and parsing details, check /docs/streaming.
Handling tool use from a mobile client
If your app needs Claude to call functions — looking up data, hitting a local database, or triggering app actions — you define tools in the request and parse tool_use blocks from the response on your backend, then execute the actual function server-side or relay the call back to the app over your own protocol. Keep tool execution logic out of the client; the app should only render results, not hold the logic that decides what the model is allowed to invoke. Full tool schema examples are in /docs/tools, and general request/response structure is in /docs/messages.
Architecture summary for an iOS app
A practical setup looks like this:
- iOS app: Swift/SwiftUI UI, Keychain-stored session token, URLSession networking layer
- Backend API: SubToAPI endpoint with an application key (
sub_live_...) scoped to your app - Claude account: your existing Anthropic access, unified behind one key and dashboard
This gives you usage metadata per app/team member, team seats if multiple developers share the same Claude access, and the ability to revoke a compromised key without rotating your core Anthropic credentials. Start with the free trial at /signup, follow /docs/quickstart for the first request, and check /pricing for Solo, Team, and Scale tiers once you're past prototyping.
Questions
Can I call the Claude API directly from Swift without a backend? Technically yes for a prototype, but any key embedded in the app binary is extractable. For anything shipping to users, route calls through a server-side proxy like SubToAPI so the real credentials never touch the device.
Does streaming work well in SwiftUI chat UIs? Yes — using URLSession.bytes(for:) to read server-sent events and updating a @Published property per token gives a smooth, incremental render without extra dependencies.
How do I manage API keys across multiple app builds (dev/staging/prod)? Issue separate application keys per environment. SubToAPI's dashboard supports per-key scoping and team seats, so you can give each build or developer a distinct sub_live_ key and revoke individually if one leaks.