使用AI代理建置iOSApp:實務指南
# 運用AI代理更快速建置iOSApp。涵蓋Claude Code、Codex CLI、Xcode 27代理、MCP、CLAUDE.md模式、hooks,以及來自8款App的經驗。
TL;DR:目前已有3種代理執行階段能為iOS交付程式碼:搭配MCP的Claude Code CLI、搭配MCP的Codex CLI,以及Xcode原生的Intelligence agents——Claude Agent、Codex,以及自Xcode 26.6起支援的Google Gemini或任何Agent Client Protocol(ACP)代理。17兩個MCP伺服器(提供82項工具的XcodeBuildMCP,以及提供20項工具的Apple
xcrun mcpbridge)讓代理能以結構化方式存取建置、測試、模擬器與除錯功能。本指南彙整了實際的CLAUDE.md模式、hook設定,以及哪些做法奏效、哪些會失靈的坦誠評估——取材自8款正式上線的iOS app,合計293個Swift檔案。32代理擅長SwiftUI view、SwiftData model、重構與建置錯誤診斷;但在修改.pbxproj、程式碼簽署與視覺除錯上表現不佳。「代理撰寫Swift」與「代理交付iOS app」之間的落差,靠的是設定而非提示詞。截至WWDC 2026(6月8日),iOS 27仍處於beta階段——截至8月10日為beta 5(24A5408d)——並新增了與代理相關的framework(Foundation Models tool-calling control、App Intents背景執行,以及全新的Core AI與Evaluations framework)。值得在代理的context中明確提及,因為在2026年6月前受訓的model不會知道它們。Xcode 26.6(2026-06-25,Swift 6.3)是目前穩定的toolchain;Xcode 27 beta(Swift 6.4、iOS 27 SDKs)則隨著iOS 27週期推進。1718
我曾以AI coding agent打造8款iOS app。不是prototype,而是已上架App Store的app,涵蓋HealthKit整合、Metal shader、SpriteKit physics、iCloud同步、Live Activities、Game Center排行榜,以及橫跨iOS、watchOS與tvOS的多平台target。這些app中的每一行Swift,不是由代理撰寫後經我審查,就是由我撰寫後交由代理重構。依我的估計,代理負責了大部分逐行撰寫工作;我則負責審查、範圍界定,以及需要人類判斷的部分(視覺細修、簽署、效能調校、App Store提交)。
這份指南是我剛開始時最希望能找到的參考資料。它涵蓋完整技術棧:該使用哪種代理執行階段、如何設定MCP伺服器以取得結構化建置存取、CLAUDE.md該寫什麼、哪些hook能防止代理毀掉您的Xcode專案,以及——更關鍵的是——代理在哪些地方會失敗、何時需要您親自接手。
重點摘要
給剛接觸AI代理的iOS開發者:
- 從Claude Code CLI + XcodeBuildMCP開始。這是最成熟的執行階段,具備最完整的MCP工具覆蓋範圍。安裝2個指令,將CLAUDE.md加入專案後,代理便能建置、測試與除錯,您不必再手動複製錯誤訊息。
- 絕不可讓代理修改.pbxproj。這是最重要的一條規則。使用PreToolUse hook封鎖對
.pbxproj與.xcodeproj/的寫入,能為您省下數小時的復原時間。 - 您的CLAUDE.md就是代理的入門文件。投入在其中的時間,會在每一次接觸專案的代理工作階段中持續回收效益。
給想將iOS納入工作流程、已有代理使用經驗的開發者:
- MCP徹底改變了iOS建置迴圈。在MCP之前,代理能寫Swift,卻無法驗證是否能編譯。有了XcodeBuildMCP後,代理能撰寫程式碼、建置、讀取結構化錯誤、修正問題並執行測試——自主完成整個流程。
- 3種執行階段各自滿足不同需求。Claude Code CLI適合深入的代理工作階段,Codex CLI適合無頭批次工作,而Xcode自身的代理——在Xcode 27中不再只是行內修正工具,新增了plug-in、MCP伺服器,以及驅動模擬器的能力。22
- Hook基礎設施可直接沿用。既有的PostToolUse formatter、PreToolUse blocker與test runner hook,只需微調路徑,即可同樣用於iOS專案。
給評估AI輔助iOS開發的團隊主管:
- 代理效能隨專案文件品質提升,而非隨專案規模提升。擁有詳盡CLAUDE.md的63檔案app,會比沒有任何說明的14檔案app產出更好的代理成果。
- .pbxproj邊界不可妥協。代理無法可靠地編輯Xcode專案檔案。您的工作流程必須納入手動將檔案新增至Xcode target的步驟。
- 坦誠的ROI:代理能處理文件完善專案的大部分實作工作——下方case study中,一款15檔案的TV app透過代理輔助在3小時內交付,便是明證。其餘工作——視覺細修、簽署、效能調校與App Store提交——仍需要人類判斷。
選擇您的路徑
| 您的需求 | 前往此處 |
|---|---|
| 首次設定MCP | MCP設定:完整配置——安裝兩個伺服器、驗證並設定代理 |
| 為iOS專案撰寫CLAUDE.md | iOS專案的CLAUDE.md模式——來自8款app的實例 |
| 比較3種代理執行階段 | 適用於iOS的3種代理執行階段——Claude Code、Codex與Xcode原生代理的比較 |
| 了解代理能做與不能做的事 | 代理擅長的工作與代理不擅長的工作 |
| 為iOS開發設定hook | iOS開發用Hook——儲存時格式化、.pbxproj保護、test runner |
| 深入參考(本頁) | 繼續閱讀——從設定到進階模式,一應俱全 |
如何使用本指南
這是一份超過3,000行的參考資料。請從符合您經驗程度的部分開始:
| 經驗程度 | 從這裡開始 | 接著探索 |
|---|---|---|
| 剛接觸iOS與代理 | 先決條件→MCP設定→您的第一個代理工作階段 | CLAUDE.md模式、哪些做法有效/無效 |
| iOS開發者,剛接觸代理 | 3種執行階段→MCP設定→CLAUDE.md | Hook、架構模式 |
| 代理使用者,剛接觸iOS | 架構模式→代理不擅長的工作→CLAUDE.md | Framework專屬context、進階工作流程 |
| 兩者皆有豐富經驗 | 進階工作流程→Hook→多平台模式 | 執行階段比較、作品集 |
目錄
- 作品集:8款App,293個檔案
- 先決條件
- 適用於iOS的3種代理執行階段
- MCP設定:完整配置
- iOS專案的CLAUDE.md模式
- 您的第一個代理工作階段
- 代理在iOS中擅長的工作
- 代理在iOS中不擅長的工作
- iOS開發用Hook
- 適合與代理搭配的架構模式
- Framework專屬Context
- 多平台模式
- 進階工作流程
- 真實案例研究
- 使用代理的專案生命週期
- 設定代理定義
- 代理輔助iOS的測試模式
- iOS專案的Context Window管理
- 疑難排解
- iOS中常見的代理錯誤及其預防方式
- 坦誠評估
- FAQ
- 快速參考卡
- 參考資料
相關資源
| 主題 | 資源 |
|---|---|
| 適用於Xcode的MCP設定(較短的部落格文章) | 兩個MCP伺服器讓Claude Code成為iOS建置系統 |
| Claude Code CLI完整參考 | Claude Code CLI:完整指南 |
| Codex CLI參考 | Codex CLI:完整指南 |
| Hook系統深入解析 | Claw的剖析:作為協調層的84個Hook |
| 代理架構模式 | 代理架構指南 |
| Mac桌面app + Remote Control | Claude Code Mac Desktop + Remote Control:CLI使用者指南 |
Apple生態系系列。共21篇正式上線文章,介紹整合Apple Intelligence、MCP、Foundation Models、Vision、Core ML與iOS 26 framework stack的SwiftUI app。內容取材自Water、Get Bananas、Return及941作品集中的其他app:
系列中心:Apple生態系系列
Agentic Apple(E4):
| 主題 | 資源 |
|---|---|
| Apple Intelligence的intent surface | App Intents是Apple通往您App的新API |
| 與iOS app並存的MCP伺服器 | 兩個代理生態系,一份購物清單 |
| 何時該使用哪一種 | App Intents與MCP工具:路由問題 |
| 裝置端LLM作為runtime功能與tooling的差異 | Foundation Models + Agentic Workflow |
| Apple開發用Hook | Apple開發用Hook |
| 跨程序狀態 | 單一事實來源:SwiftData + MCP + iCloud |
Framework(E2/E3):
| 主題 | 資源 |
|---|---|
| Foundation Models裝置端LLM | Foundation Models裝置端LLM |
| Vision framework(CV primitive) | Vision Framework:內建功能一覽 |
| Core ML inference模式 | Core ML裝置端Inference |
| RealityKit空間心智模型 | RealityKit與空間心智模型 |
| SwiftUI內部運作 | SwiftUI的組成 |
| Symbol Effects動畫詞彙 | Symbol Effects:SwiftUI內建動畫詞彙 |
| iOS 26+上的Liquid Glass | SwiftUI中的Liquid Glass:3種模式 |
已交付程式碼(E1):
| 主題 | 資源 |
|---|---|
| Live Activities狀態機 | Live Activities狀態機 |
| watchOS runtime契約 | watchOS Runtime契約 |
| SwiftData schema紀律 | SwiftData Schema紀律 |
| HealthKit + SwiftUI模式 | iOS 26上的HealthKit + SwiftUI |
| 多平台SwiftUI | 5個Apple平台,3個共用檔案 |
| XcodeBuildMCP整合 | 兩個MCP伺服器,一個Xcode專案 |
綜合(E5):
| 主題 | 資源 |
|---|---|
| iOS app的3個層面 | iOS App的3個層面 |
| 平台target決策 | Apple平台矩陣 |
| 我拒絕撰寫的內容 | 我拒絕撰寫的內容 |
iOS 27與WWDC 2026:您的代理現在能建置什麼
WWDC 2026(2026年6月8日)讓iOS 27進入beta階段。本指南中的代理開發工作流程不變:您仍透過MCP操作Claude Code、Codex或Xcode的Intelligence代理;仍會撰寫CLAUDE.md,並以hooks管控具破壞性的操作。改變的是代理所面對的功能範圍。iOS 27推出多個與代理相關的新framework;實務上,應刻意讓程式設計代理使用它們,因為在2026年6月前訓練的模型不會知道這些功能存在。iOS 26仍是正式發行版本;若要針對iOS 27 beta SDK建置,請將下列項目視為目標。
與代理相關的iOS 27功能範圍,以及各自的深入參考資料:
- Foundation Models新增了工具呼叫控制。
GenerationOptions.ToolCallingMode可讓您針對每個請求控制裝置端模型呼叫工具的積極程度,而且framework能在首次呼叫後切換模式,以限制單一請求的工具活動。Vision framework現在提供現成的OCRTool與BarcodeReaderTool,可直接附加至LanguageModelSession,無須自行撰寫辨識程式碼。請參閱Foundation Models in iOS 27: Tool-Calling Control。12 - App Intents突破了30秒限制。
LongRunningIntent(透過performBackgroundTask(options:operation:),且必須回報進度)可延長intent的背景執行時間,用於同步、檔案處理與裝置端推論;SyncableEntity讓AppEntity具備跨裝置身分;IndexedEntityQuery讓系統能要求您的query修復其Spotlight索引。請參閱App Intents in iOS 27: Background, Sync, Spotlight。13 - Core AI是用來在Apple Silicon上執行模型的新framework。當您自行帶入模型,而非使用Apple的系統模型時,它位於Foundation Models之下。請參閱Core AI: Running Models on Apple Silicon。14
- Evaluations是用於模型品質的XCTest。這是一個新的framework(macOS 27),可將模型輸出品質的衡量納入測試套件;這正是發行由代理協助建置的AI功能所缺少的一環。請參閱Evaluations: XCTest for Model Quality。15
- SwiftData、HealthKit與SwiftUI也同步演進。SwiftData在iOS 27新增觀察與歷程;HealthKit新增運動區間與新型別;SwiftUI的iOS 27新增功能則一如往常地涵蓋廣泛。請參閱SwiftData in iOS 27、HealthKit in iOS 27,以及What’s New in SwiftUI for iOS 27。16
iOS 27工作的工具鏈是Xcode 27 beta。Xcode 27於WWDC首日(6月8日,build 27A5194q)以beta形式推出,截至8月10日已來到beta 5(27A5237l)。它包含Swift 6.4與iOS 27/iPadOS 27/tvOS 27/watchOS 27/macOS 27/visionOS 27 SDKs,且需要macOS Tahoe 26.4或更新版本。18有4項release notes內容與代理工作流程相關:Coding Intelligence新增plan mode——說明文件透過「Implement the plan?」確認列的known issue(178673449)提及此功能,因此請等待代理完成串流輸出後,再確認或關閉計畫;RenderPreview MCP工具現在可渲染Preview群組(174692209),也能以不同localization預覽您的UI(181040291);面向代理的「Prepare Project for Localization」工具現在會回報因不再出現於原始碼而遭移除的String Catalog keys(179755385);此外,若app以Xcode 26.4或更早版本建置,Address Sanitizer可能無法在27.0目標上啟動——執行ASan時請使用Xcode 26.5+(178072780)。18Beta 5另外新增兩項與此處相關的功能。代理現在可驗證watchOS apps,包含「旋轉及按下Digital Crown,以及按下側邊按鈕與Action按鈕(Apple Watch Ultra)」(181147968)——這是Apple代理首次能操作watch app的實體輸入,補足了本指南所記錄之視覺驗證缺口的一部分。此外,Apple預覽了不再需要開啟Xcode的MCP server;請參閱下方Apple MCP server章節。22MCP工具也已跟上beta的步調:XcodeBuildMCP v2.7.0(2026-07-23)讓其UI automation工具能透過Device Hub完整支援Xcode 27 simulators,包括啟動simulator視窗及鍵盤控制——在該版本之前,runtime UI automation僅能穩定用於Xcode 26 simulators,使得在iOS 27 beta上由代理進行的UI驗證仍得仰賴手動操作。21
操作者應記住的道理,與本指南其餘部分一致:代理撰寫程式碼,而您補足它所欠缺的知識。面對iOS 27 betas,這表示要在prompt或CLAUDE.md中指名這些framework,並將代理連結至Apple文件;否則模型會套用每個API在iOS 26中的形式。本指南其餘內容(runtimes、MCP、hooks與失敗模式)皆可原封不動地適用於iOS 27工作。
作品集:8個App、293個檔案
在深入設定之前,先說明本指南的經驗來源。這些不是玩具專案——它們涵蓋5個Apple frameworks、3個平台,以及iOS複雜度的完整光譜:從14個檔案的運動追蹤器,到63個檔案的多平台冥想計時器。
| App | 技術堆疊 | 檔案數 | 複雜度 |
|---|---|---|---|
| Banana List | SwiftUI + SwiftData + iCloud Drive同步 +供Claude Desktop使用的MCP server | 53 | 完整CRUD、iCloud同步、自訂MCP server,將app資料提供給Claude Desktop |
| Ace Citizenship | SwiftUI學習app + FastAPI backend | 26 | Client-server、REST API整合、測驗引擎 |
| TappyColor | SpriteKit顏色配對遊戲 | 30 | 遊戲迴圈、物理效果、觸控處理、粒子效果 |
| Return | 禪修計時器——iOS 26+、watchOS、tvOS | 63 | HealthKit、Live Activities、Watch延長執行時間、TV焦點導覽、iCloud session同步 |
| amp97 | Metal shaders +音訊視覺化 | 41 | 自訂Metal render pipeline、音訊分析、即時GPU計算 |
| Reps | SwiftUI + SwiftData運動追蹤 | 14 | 最小可行app、清晰的SwiftData模式 |
| Water | SwiftUI + SwiftData + Metal + HealthKit飲水追蹤 | 34 | Metal流體模擬、HealthKit飲水量記錄、widget |
| Starfield Destroyer | SpriteKit + Metal太空射擊遊戲 | 32 | 99個關卡、8艘飛船、Game Center排行榜、Metal後處理 |
檔案數量為何重要:代理的成效與專案的可理解性相關,而非專案大小。Return(63個檔案)比amp97(41個檔案)產生更好的代理輸出,因為Return具備詳細的CLAUDE.md,包含檔案註解、架構圖與明確模式。無論文件品質如何,amp97的Metal shaders本質上都更難讓代理推理。
先決條件
在為iOS開發設定任何代理runtime之前:
App Store Connect截止期限:自2026-04-28起,上傳至App Store Connect的app必須以Xcode 26或更新版本建置,並使用適用於iOS 26、iPadOS 26、tvOS 26、visionOS 26或watchOS 26的SDKs。26(macOS提交不受此要求限制。)若您的團隊仍在使用Xcode 16.x,本指南中的代理輔助工具鏈同時也是一項推動升級的力量——反正下方任何MCP servers都無法在沒有Xcode 26.3+的情況下運作。
必要項目:
- macOS 15+(Sequoia)或macOS Tahoe(Xcode 26.6需要macOS Tahoe 26.2+;Xcode 27 beta需要Tahoe 26.4+)
- 已安裝並設定Xcode 26.3+(xcrun mcpbridge最低版本);建議使用Xcode 26.6+。Xcode 26.6(2026-06-25,build 17F113)是最新穩定版,帶來3項與代理相關的Coding Intelligence變更:Google Gemini作為coding-assistant provider、Agent Client Protocol(ACP)支援,以及preview MCP工具中的variant rendering——淺色/深色、方向、字體大小;它也修正了2個代理turn當機問題,以及代理提問時發生的卡住問題,並提供Swift 6.3與iOS 26.5-generation SDKs。1726.5工作流程的升級——coding assistant中的訊息佇列與澄清問題支援——以及26.4的Swift Testing影像附件、recorded-issue嚴重度、附帶crashlogs的UI-test當機警告,與String Catalog editor改良,全都延續至此版本。2728先前的穩定版本為26.5(2026-05-11,build 17F42)與26.4.1(2026-04-16,build 17E202)。29
- 至少安裝一個iOS Simulator runtime
- 一個Anthropic API帳戶(供Claude Code使用)或OpenAI帳戶(供Codex使用)
建議項目:
- 已安裝SwiftFormat(brew install swiftformat)——供format-on-save hooks使用
- 已安裝SwiftLint(brew install swiftlint)——選用,但有助於強制執行樣式規範
- 熟悉terminal——3個runtimes全都透過command line運作或與其整合
驗證您的Xcode安裝:
# Check Xcode version
xcodebuild -version
# Expected: Xcode 26.3 or later (26.6+ recommended)
# Check available simulators
xcrun simctl list devices available
# Expected: at least one iPhone simulator
# Verify xcrun mcpbridge is available
xcrun mcpbridge --help
# Expected: usage information (not "command not found")
如果xcrun mcpbridge回傳「command not found」,表示您需要Xcode 26.3或更新版本。請透過App Store或developer.apple.com安裝或更新Xcode。請注意:xcode-select --install僅會安裝Command Line Tools,其中不包含mcpbridge——您需要完整的Xcode.app。
適用於iOS的3種Agent執行環境
3種不同的執行環境都能撰寫、建置及測試iOS程式碼。它們無法互相取代——各自具備不同優勢、不同的MCP整合模式,以及適合的使用情境。
1. Claude Code CLI
它是什麼:Anthropic的終端機型代理式程式設計助理。它會讀取您的程式碼庫、執行指令、修改檔案,並透過MCP連接外部工具。7
MCP整合:完整支援XcodeBuildMCP與Apple的Xcode MCP。Agent會透過MCP通訊協定探索工具,並以結構化參數呼叫它們。兩個伺服器合計提供82+20項工具。
設定:
# Install Claude Code (if not already installed)
claude --version # verify installation
# Add XcodeBuildMCP (82 tools — builds, tests, simulators, debugging)
claude mcp add XcodeBuildMCP \
-s user \
-e XCODEBUILDMCP_SENTRY_DISABLED=true \
-- npx -y xcodebuildmcp@latest mcp
# Add Apple Xcode MCP (20 tools — file ops, diagnostics, Swift REPL, previews)
claude mcp add --transport stdio xcode \
-s user -- xcrun mcpbridge
替代方案——xcodebuildmcp init自動安裝程式(v2.1.0+,2026年2月23日):
若想略過手動設定MCP連線,XcodeBuildMCPv2.1.0+提供init子指令,可自動偵測Claude Code、Cursor或Codex,並一步完成Agent技能與MCP設定的安裝:
xcodebuildmcp init
# Or without a global install:
npx -y xcodebuildmcp@latest init
旗標:--print(將設定寫入stdout,供不支援的用戶端使用)、--uninstall(移除)。如果想明確掌控要連接哪些MCP伺服器及其設定範圍,請略過此方式;上方手動執行的claude mcp add指令可讓您保有這項控制權。30
最適合用於:深度實作工作階段——建置新功能、跨多個檔案重構、除錯複雜問題,以及自主執行建置、測試、修正迴圈。Claude Code的1M內容視窗(搭配Opus 5)讓Agent能在工作記憶中保留大部分中小型iOS專案——依我的經驗,視檔案大小而定,大約可處理50個檔案。25
典型工作階段:
You: Add a new SettingsView with toggles for notifications and haptic feedback.
Use the existing Settings.swift pattern from TimerManager.
Build for simulator after implementation and fix any errors.
Claude: [reads Settings.swift, TimerManager.swift, existing views]
[creates SettingsView.swift]
[calls build_sim via MCP]
[reads structured error: missing import HealthKit]
[fixes import]
[calls build_sim again — success, 0 errors, 1 warning]
[calls test_sim — all tests pass]
與MCP導入前工作流程的關鍵差異在於:Agent不再要求您手動建置或貼上錯誤輸出。建置、錯誤、修正迴圈可自主完成。
2. Codex CLI
它是什麼:OpenAI的終端機型程式設計Agent。概念上類似Claude Code,但它執行OpenAI的Codex模型,且採用不同的權限模型。目前陣容包括GPT-5.6 Sol(旗艦款,最擅長複雜程式設計)、GPT-5.6 Terra(均衡的日常預設選項)與GPT-5.6 Luna(最快且成本最低),另有GPT-5.3 Codex Spark作為僅文字的研究預覽版。GPT-5.4與GPT-5.4-mini將於2026年8月31日從Codex退役——請分別將這些設定遷移至Terra與Luna。23
MCP整合:Codex透過codex mcp add指令支援MCP。Apple的Xcode MCP可直接使用:
# Add Apple Xcode MCP to Codex
codex mcp add xcode -- xcrun mcpbridge
XcodeBuildMCP也能透過相同的npx指令與Codex搭配使用:
# Add XcodeBuildMCP to Codex
codex mcp add XcodeBuildMCP -- npx -y xcodebuildmcp@latest mcp
最適合用於:無頭批次作業、CI/CD整合,以及希望由不同模型家族提供第二意見的工作。Codex的沙箱模式會在隔離環境中執行程式碼,適合可能修改狀態的破壞性作業,例如執行測試套件。
與Claude Code的主要差異:
- 使用OpenAI模型,而非Claude模型
- 內容視窗大小與Token成本結構不同
- 採取沙箱優先的權限模型(預設限制較多)
- MCP生態系較小(經測試的社群伺服器較少)
- 提供Hooks系統(v0.119.0+),但成熟度不及Claude Code——事件類型較少,且沒有條件式if欄位
何時該在iOS工作中選擇Codex而非Claude Code:
當您需要模型多樣性時,請使用Codex——讓第二個Agent審查第一個Agent撰寫的程式碼,能捕捉不同類型的錯誤。協作工作流程(Claude負責建置,Codex負責審查)對iOS特別有效,因為某個模型家族認為正確的SwiftUI模式,可能存在另一個模型家族才能發現的細微問題。Metal shader與並行模式尤其適合採用雙模型審查。
3. Xcode原生Agent
它是什麼:Apple將AI程式設計Agent直接整合至Xcode的Intelligence面板。截至Xcode 26.3,您可在Xcode Settings>Intelligence中,將Claude Agent與Codex設定為智慧功能提供者。10Xcode 26.6擴大了支援陣容:Google Gemini現已可在程式設計助理中使用(171990272),而Xcode新增了Agent Client Protocol(ACP)支援(178294840)——原本只有兩個提供者的整合,如今已擴充為3個提供者,加上一個開放通訊協定,讓所有相容ACP的Agent都能接入Intelligence面板。17
設定:
- 開啟Xcode 26.3+
- 前往Settings>Intelligence
- 新增提供者:
- Claude:選取「Claude Agent」,輸入您的Anthropic API金鑰
- Codex:選取「Codex」,輸入您的OpenAI API金鑰
- Gemini:選取「Google Gemini」(Xcode 26.6+)
- 其他服務:連接相容ACP的Agent(Xcode 26.6+)
- Agent會顯示於Intelligence側邊欄,並可在程式碼中直接呼叫
最適合用於:快速的內嵌編輯、具備Agent級推理能力的程式碼補全,以及偏好不離開Xcode的開發者。原生整合代表Agent可直接存取Xcode的專案脈絡——開啟的檔案、建置目標、Scheme設定——無須透過MCP橋接。
相較於CLI Agent的限制——在Xcode 26.x中: - 沒有Hooks系統——無法強制在儲存時格式化,或封鎖寫入.pbxproj - 不會載入CLAUDE.md——Agent不會讀取專案層級的設定檔 - 自主性有限——Agent只會處理目前檔案或選取範圍,無法涵蓋整個專案 - 無法委派子Agent——複雜的多步驟工作無法平行處理 - 無法設定MCP伺服器——Agent僅使用Xcode內建工具
Xcode 27推翻了上述大部分限制。自beta 1(6月8日)起,Xcode的Agent已從內嵌助理轉變為擴充平台:22
- 外掛程式:「Xcode中的Agent現在可透過包含技能、MCP伺服器與ACP Agent設定的外掛程式擴充。技能可作為slash commands呼叫,並支援補全。」(178289210)——因此「僅限內建工具」與「無法設定MCP」的限制已不復存在。
- Simulator控制:Agent「現在可啟動Simulator、安裝及啟動App、合成觸控事件,並擷取螢幕截圖以驗證UI行為」(175179787);在beta 5中,它們還能操作watchOS硬體輸入(181147968)。
- Debugger存取:Xcode MCP伺服器新增工具,可操控執行狀態、讀取Debugger主控台、切換Scheme與執行目的地,以及檢查或修改「建置設定、編譯器旗標、權限與Info.plist金鑰」(176935844)。
- 檔案系統安全層「會監控並控制程式設計Agent及其所啟動的所有處理程序對檔案系統的存取」(178289431),另有第一級規劃功能(172857081),以及涵蓋當機、卡頓、耗電與啟動問題的專案洞察(177568662)。
由176935844直接衍生的一項警告:Xcode的Agent現在可以編輯建置設定、權限與Info.plist金鑰。本指南透過PreToolUse hook建立的.pbxproj保護機制不適用於Xcode內,因為hook位於您的CLI Agent設定中,而非Apple的設定中。如果您仰賴此hook作為安全防線,請注意它對Intelligence面板沒有管轄權。
何時該使用Xcode原生Agent:
適合快速且範圍明確的編輯,此時切換至終端機反而增加負擔。「為這個model新增一個computed property。」「為這個function撰寫unit test。」「將這個view重構為使用@Observable。」適用於只涉及1或2個檔案,且不需要建置與測試迴圈的工作。
任何需要建置、測試、多檔案重構或自主修正錯誤的工作,請使用搭配MCP的CLI Agent。
執行環境比較矩陣
| 功能 | Claude Code CLI | Codex CLI | Xcode原生(26.x→27) |
|---|---|---|---|
| MCP支援 | 完整(102項工具) | 完整(102項工具) | 26.x:僅限內建工具;27:透過外掛程式使用MCP伺服器22 |
| Hooks系統 | 有(成熟) | 有(基本,v0.119.0+) | 無 |
| CLAUDE.md/專案設定 | 有 | codex.md等效檔案 | 無 |
| 自主建置、測試、修正 | 有(透過MCP) | 有(透過MCP) | 26.x:部分支援(僅限內嵌);27:可啟動Simulator並驗證UI22 |
| 子Agent委派 | 有(最多10個平行) | 無 | 無 |
| 內容視窗 | 1M Token(Opus 5) | 依模型而異 | 依提供者而異 |
| 多檔案作業 | 完整程式碼庫存取 | 完整程式碼庫存取 | 26.x:目前檔案/選取範圍;27:具備規劃的全專案作業22 |
| .pbxproj保護 | 透過Hooks | 手動 | 不適用(原生使用Xcode) |
| 儲存時格式化 | 透過PostToolUse hooks | 外部工具 | Xcode設定 |
| 離線能力 | 無 | 無 | 無 |
| 成本模式 | Anthropic API用量 | OpenAI API用量 | 提供者API用量 |
建議:以Claude Code CLI作為主要執行環境。使用Xcode原生Agent處理快速內嵌編輯。使用Codex CLI進行審查與批次作業。三者相輔相成,而非彼此競爭。
MCP設定:完整配置
MCP(Model Context Protocol)能將代理從「撰寫Swift並期待您自行建置」轉變為「撰寫Swift、建置、讀取結構化錯誤並修正」。2本節比這篇部落格文章11更深入——涵蓋兩種伺服器、所有安裝方式、驗證步驟,以及確保工具確實被使用的代理設定。
XcodeBuildMCP:無頭iOS開發的82項工具
XcodeBuildMCP將xcodebuild、xcrun simctl與LLDB封裝為82項結構化MCP工具(公告的工具清單經驗證,自v2.6.2至v2.7.0維持不變),分為12類工作流程。31921此專案的正式所在地是getsentryGitHub組織——由Sentry維護;原本的cameroncooke/XcodeBuildMCPURL如今會重新導向至此,在較舊文章引用舊網址時尤其重要。21即使未執行Xcode也能運作——整個建置、測試、偵錯循環都透過Apple的命令列工具以無頭方式執行。有兩項工具清單重點值得了解:預設stdio工作階段會公開模擬器工作流程中的24項工具,並將其餘工具排除在代理的內容脈絡外——設定XCODEBUILDMCP_ENABLED_WORKFLOWS(以下表中的類別名稱,以逗號分隔)即可載入更多工具;此外,同一引擎也提供CLI版本(xcodebuildmcp tools會回報100個指令,其中72個為正式指令),若您想在不使用MCP的情況下進行相同操作即可採用。9
安裝選項:
# Option 1: Via npx (recommended — always uses latest version)
claude mcp add XcodeBuildMCP \
-s user \
-e XCODEBUILDMCP_SENTRY_DISABLED=true \
-- npx -y xcodebuildmcp@latest mcp
# Option 2: Via Homebrew (pinned version, manual updates)
brew install xcodebuildmcp
claude mcp add XcodeBuildMCP \
-s user \
-e XCODEBUILDMCP_SENTRY_DISABLED=true \
-- xcodebuildmcp mcp
# Option 3: Project-scoped (omit -s user)
claude mcp add XcodeBuildMCP \
-e XCODEBUILDMCP_SENTRY_DISABLED=true \
-- npx -y xcodebuildmcp@latest mcp
-s user旗標會讓伺服器在所有專案中全域可用。若只想在iOS專案使用MCP、而不在網頁專案使用,請省略此旗標,改採專案範圍的安裝。
-e XCODEBUILDMCP_SENTRY_DISABLED=true環境變數會停用當機報告遙測。XcodeBuildMCP預設包含Sentry,會傳送含有檔案路徑的錯誤資料。除非您希望為專案提供診斷資訊,否則建議選擇退出。1
工具清單(12類工作流程共82項工具——每類列出代表性工具):
| 類別 | 工具 | 功能 |
|---|---|---|
| project-discovery | discover_projs, list_schemes, show_build_settings, get_app_bundle_id |
尋找.xcodeproj/.xcworkspace檔案、列出scheme、檢查建置設定 |
| simulator | build_sim, build_run_sim, test_sim, install_app_sim, launch_app_sim |
依檔案與行號輸出結構化錯誤/警告來建置與測試;在模擬器上安裝並啟動 |
| simulator-management | list_sims, boot_sim, open_sim, erase_sims, set_sim_appearance, set_sim_location, session_set_defaults |
啟動、清除及設定模擬器(外觀、位置、狀態列) |
| device | build_device, test_device, list_devices, install_app_device, launch_app_device |
實體裝置的建置、測試、部署與管理 |
| macos | build_macos, build_run_macos, test_macos |
針對Mac目標進行相同的建置、測試循環 |
| swift-package | swift_package_build, swift_package_test, swift_package_run |
不需.xcodeproj即可執行SwiftPM建置/測試/執行 |
| coverage | get_coverage_report, get_file_coverage |
從.xcresult套件取得各目標與函式層級的涵蓋率 |
| debugging | debug_attach_sim, debug_breakpoint_add, debug_stack, debug_variables, debug_lldb_command, debug_continue, debug_detach |
完整LLDB整合,支援中斷點與變數檢查 |
| ui-automation | snapshot_ui, wait_for_ui, batch, tap, drag, swipe, type_text, gesture, screenshot, record_sim_video |
使用穩定的元素參照進行執行階段UI自動化(v2.6.0+),並支援視覺擷取 |
| project-scaffolding | scaffold_ios_project, scaffold_macos_project |
從範本建立新的iOS/macOS專案 |
| utilities | clean |
清理建置產物 |
| xcode-ide | xcode_ide_list_tools, xcode_ide_call_tool |
透過XcodeBuildMCP探索及呼叫僅限Xcode-IDE的MCP工具(見下文) |
日常工作中最重要的工具:
-
build_sim——您會呼叫它數百次。它會傳回JSON,其中的錯誤依檔案、行號與嚴重程度分類。代理會讀取錯誤、前往檔案並修正,您無須介入。 -
test_sim——傳回每個測試方法的結果。代理會確切知道哪個測試失敗及其原因,而不是只得到「測試失敗」。 -
list_sims+boot_sim——無須記住xcrun simctl旗標即可管理模擬器。代理會找出可用runtime並挑選合適的裝置。 -
discover_projs+list_schemes——專案檢視。代理不必猜測您的scheme名稱或workspace結構。 -
debug_attach_sim+debug_stack+debug_variables——遠端LLDB偵錯。代理能設定中斷點、檢查變數並逐步執行程式碼,您不必開啟偵錯工具。
v2.6.0的變更(2026-06-01)——執行階段UI自動化:
v2.6.0版本以可重複使用的內容脈絡取代一次性螢幕截圖,重建了UI自動化機制。19snapshot_ui現在會傳回穩定的元素參照與畫面雜湊值,並接受sinceScreenHash,讓代理可在畫面未變更時跳過完整快照。3項新工具補齊了整個流程:wait_for_ui會輪詢至述詞成立(元素存在、啟用狀態、焦點、可見文字或版面穩定),不再讓代理以sleep猜測;batch會在單一呼叫中依序執行多個元素參照動作;drag則針對工作表與清單捲動提供元素參照拖曳手勢。type_text新增replaceExisting,可取代欄位原有值而非附加文字;候選控制項會依輔助使用資料排序;結構化結果現在也包含nextSteps提示(此版本將結果schema升級為v2;v2.7.0其後已將建置/測試結果改為schemaVersion: 3——見下文)。設定XCODEBUILDMCP_HEADLESS_LAUNCH=true可在背景啟動App,不會搶走macOS焦點——這正是可讓代理工作階段持續執行,與不斷將Simulator視窗拉到前景之間的差異。在一項可重現的天氣App任務中,專案自身的基準測試宣稱,相比v2.6之前的流程,整體耗時約減少70%、token減少68%、工具呼叫減少76%——這是專案方的數據,並非獨立測量;但其機制(跳過未變更快照、批次處理同畫面動作)正是UI自動化token消耗的主要來源。19
v2.7.0的變更(2026-07-23)——Xcode 27模擬器、schema v3、遵循scheme的建置:
v2.7.0版本雖然比2.6.0小,但升級前有一項破壞性變更與一項行為變更值得了解。21重點是:UI自動化工具現在能透過Device Hub完整支援Xcode 27模擬器,包括啟動模擬器視窗與鍵盤控制——填補了執行階段UI自動化過去僅能可靠地對Xcode 26模擬器運作的缺口。破壞性變更:建置與測試工具現在會傳回schemaVersion: 3結構化結果(自2.6.0起原為v2)——凡是您撰寫過、驗證或解析固定版本2結果的內容,都需要更新。行為變更:當省略configuration時,建置、測試、清理及App路徑工具現在會遵循scheme動作的設定,而不再一律預設為Debug——若scheme的Test動作設為Release,未指定設定的test_sim現在會建置Release;若工作流程依賴特定設定,請明確傳入configuration。其他較小但實用的改進包括:可重複使用的.xctestproducts測試準備套件,讓測試無須重新建置即可再次執行,同時每次執行仍產生新的.xcresult;工作階段預設extraArgs可讓您每個工作階段設定一次共用xcodebuild旗標,不必每次呼叫重複傳入;新的xcodebuildmcp purgeCLI指令可回報並清理XcodeBuildMCP的workspace儲存空間(預設為dry-run,需明確選擇才會刪除);此外也修正了MCP用戶端等待工具可用時長達10至17秒的問題——這可能使短暫健康檢查誤報連線失敗。21
Apple Xcode MCP:橋接至Xcode的20項工具
Apple的MCP伺服器隨Xcode 26.3透過xcrun mcpbridge提供。4它經由XPC(Apple的跨程序通訊框架)與正在執行的Xcode程序通訊,公開任何CLI工具皆無法存取的內部狀態。5
安裝:
# Standard installation (global)
claude mcp add --transport stdio xcode \
-s user -- xcrun mcpbridge
# For Codex CLI
codex mcp add xcode -- xcrun mcpbridge
需要Xcode 26.3+與正在執行的Xcode程序。若Xcode未開啟,透過此伺服器進行的每個MCP呼叫都會失敗或卡住。XcodeBuildMCP沒有此限制。
Xcode 27 beta 5預覽版提供了擺脫此限制的方法。Apple新增了「不需開啟Xcode workspace即可執行的新MCP伺服器體驗」,以sudo xcrun mcp-server enable啟用,並以xcrun mcp-server status檢查狀態。此預覽版也讓您可授予具程式碼簽署的代理持久權限,使其在目錄樹內工作,而不必每次重新核准。對於無人值守的執行作業,sudo xcrun mcp-server enable --unsafe-always-allow-all-agents會預先核准一切——Apple明確表示這「不建議用於桌面前操作的設定」,我也同意:這會移除防止代理進入您原本無意公開目錄的核准步驟。應將整個功能面視為早期預覽,並在它脫離預覽前繼續以XcodeBuildMCP作為無頭路徑。22
工具清單(5類共20項工具):
| 類別 | 工具 | 功能 |
|---|---|---|
| 檔案操作 | XcodeRead, XcodeWrite, XcodeUpdate, XcodeGlob, XcodeGrep |
在Xcode專案內容脈絡中讀取/寫入檔案 |
| 建置與測試 | BuildProject, GetBuildLog, RunAllTests, RunSomeTests |
使用Xcode內部建置系統進行建置與測試 |
| 診斷 | XcodeListNavigatorIssues, XcodeRefreshCodeIssuesInFile |
即時程式碼診斷(不僅是建置錯誤) |
| 程式碼與文件 | ExecuteSnippet, DocumentationSearch |
Swift REPL執行與Apple文件搜尋 |
| 預覽 | RenderPreview |
無頭SwiftUI預覽轉譯 |
Apple MCP獨有的工具(XcodeBuildMCP無法使用):
-
DocumentationSearch——搜尋Apple開發人員文件,包括WWDC場次。針對Apple API問題,比網頁搜尋更快且更可靠。詢問「HKQuantityType(.dietaryWater)是否有效?」即可從來源取得明確答案。 -
ExecuteSnippet——在專案內容脈絡中執行Swift REPL。代理可驗證API行為、測試型別轉換,以及驗證運算式,不必建置完整App。 -
RenderPreview——以無頭方式轉譯SwiftUI預覽。代理可檢查檢視是否能無錯誤轉譯,但無法判斷視覺正確性(轉譯結果會以資料形式回傳,而非經過視覺檢查)。截至Xcode 26.6,預覽MCP工具(26.6版本說明稱其為「Preview Snapshot」)能轉譯變體——淺色/深色外觀、直向/橫向方向與文字大小覆寫(178831772)——因此代理可一次驗證檢視在不同外觀下的狀態。17Xcode 27 beta進一步擴充:可轉譯Preview群組,並以不同在地化設定進行預覽。18 -
XcodeListNavigatorIssues——傳回Xcode分析器的即時診斷,而不僅是建置錯誤。可捕捉建置系統未顯示的未使用變數、可能的retain cycle與棄用警告等問題。
為何兩種伺服器都需要
兩者在建置與測試方面有所重疊,但本質上不同:
┌─────────────────────────────────────────────────────────────────┐
│ MCP TOOL COVERAGE │
├─────────────────────────────────────────────────────────────────┤
│ │
│ XcodeBuildMCP (82 tools) Apple Xcode MCP (20 tools) │
│ ┌─────────────────────┐ ┌─────────────────────┐ │
│ │ Standalone │ │ Requires Xcode │ │
│ │ (no Xcode process) │ │ (XPC bridge) │ │
│ │ │ │ │ │
│ │ ✓ Simulators │ BOTH │ ✓ Documentation │ │
│ │ ✓ Real devices │ ┌─────┐ │ ✓ Swift REPL │ │
│ │ ✓ LLDB debugging │ │Build│ │ ✓ SwiftUI previews │ │
│ │ ✓ UI automation │ │Test │ │ ✓ Live diagnostics │ │
│ │ ✓ Project scaffold │ └─────┘ │ ✓ Analyzer issues │ │
│ │ ✓ Screenshot │ │ │ │
│ └─────────────────────┘ └─────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
XcodeBuildMCP適用於:建置、測試、偵錯循環。它無須開啟Xcode、消耗較少系統記憶體,並提供更豐富的模擬器與裝置管理功能。這是您的主要建置工具。
Apple Xcode MCP適用於:文件查詢、Swift REPL驗證、SwiftUI預覽轉譯與即時診斷。需要這些功能的工作階段,請保持Xcode開啟。
實務上:我約有90%的MCP呼叫使用XcodeBuildMCP,而Apple Xcode MCP則用於文件與REPL驗證。代理會將XcodeBuildMCP作為建置與測試的預設工具,因為它更快(沒有Xcode程序負擔)且更可靠(不依賴XPC)。
雙伺服器的界線正在淡化。XcodeBuildMCP2.6.x新增xcode-ide代理類別:xcode_ide_list_tools可探索僅限Xcode-IDE的MCP功能,而xcode_ide_call_tool可呼叫它們(它們會以xcode_tools_*名稱呈現,例如xcode_tools_documentationsearch),因此單一XcodeBuildMCP註冊現在也能存取Apple的IDE端工具。19真正重要的限制沒有改變:這些代理呼叫仍需要正在執行的Xcode程序,與直接註冊xcrun mcpbridge完全相同。若希望Apple工具作為代理工具清單中的一級工具,請同時註冊兩種伺服器;當您只想登錄一個伺服器且僅偶爾讀取IDE資料時,代理功能最有用。
驗證
安裝兩種伺服器後,請確認它們已連線:
# List all configured MCP servers
claude mcp list
# Expected output includes:
# XcodeBuildMCP: npx -y xcodebuildmcp@latest mcp - Connected
# xcode: xcrun mcpbridge - Connected
如果伺服器顯示「Disconnected」或未出現:
-
XcodeBuildMCP未連線:請確認已安裝Node.js(
node --version)。npx指令需要Node.js 18+。 -
Apple Xcode MCP未連線:請確認已安裝Xcode 26.3+,且
xcrun mcpbridge指令可在終端機中執行。至少開啟一次Xcode以接受授權合約。 -
兩者皆未出現:重新啟動Claude Code(在新的終端機執行
claude)。在工作階段中途註冊的MCP伺服器,可能要重新啟動後才會出現。
教導代理使用MCP
安裝MCP伺服器是必要條件,但仍不夠。若沒有明確指引,代理可能退回使用Bash執行xcodebuild(輸出沒有結構、浪費內容脈絡token),或以網頁搜尋Apple文件(較慢且較不可靠)。
請將以下內容加入CLAUDE.md或代理定義:
## Build & Test — Always Use MCP
Prefer MCP tools over raw shell commands for ALL build operations:
- **Build**: `build_sim` / `build_device` (NOT `xcodebuild` via Bash)
- **Test**: `test_sim` / `test_device` (NOT `xcodebuild test` via Bash)
- **Simulators**: `list_sims`, `boot_sim`, `open_sim` (NOT `xcrun simctl` via Bash)
- **Debug**: `debug_attach_sim`, `debug_stack`, `debug_variables`
- **Apple docs**: `DocumentationSearch` (NOT WebSearch for Apple APIs)
- **Swift verification**: `ExecuteSnippet` (NOT `swift` via Bash)
- **Previews**: `RenderPreview` for headless SwiftUI verification
MCP returns structured JSON. Bash returns unstructured text.
Structured data means fewer tokens consumed and better error diagnosis.
此指引能確保代理優先使用MCP工具。否則,您會看到代理透過Bash組合冗長的xcodebuild指令,耗費數千個內容脈絡token解析輸出,有時還會誤判真正的錯誤。6
XcodeBuildMCPv2.7.0的一項行為變更也應納入本節的心智模型:省略configuration時,建置、測試、清理與App路徑工具現在會遵循scheme動作的設定,而不再一律採用Debug。21多數scheme會以Debug執行與測試,因此大多數專案不會察覺差異——但若scheme動作設為Release(常見於效能分析scheme或接近封存的設定),未指定設定的build_sim或test_sim現在會建置Release。若您的CLAUDE.md或hooks假設使用Debug產物,請在工具呼叫中明確指定,或以session_set_defaults每個工作階段設定一次。
長時間建置:Claude Code現在會將其移至背景
兩個Claude Code版本改變了工作階段中長時間建置的樣貌。自v2.1.212(2026-07-16)起,任何執行超過2分鐘的MCP工具呼叫都會自動移至背景,使工作階段保持可用;可透過CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS設定門檻,或停用此行為。20實際專案中的乾淨建置與完整測試執行,經常使build_sim/test_sim超過2分鐘,因此預期代理會在建置於背景完成時持續工作——讀取檔案、規劃下一次修改——而非阻塞整個回合。配套修正同樣重要:在v2.1.206(2026-07-09)之前,透過--mcp-config或.mcp.json設定的各伺服器request_timeout_ms會在全新工作階段遭到忽略,因此長時間MCP呼叫會在預設60秒時逾時——典型症狀是第一次乾淨建置逾時,但重試後「自行修復」。20若您曾以包裝腳本或預熱建置來規避任一行為,現在可以刪除這些權宜措施。
iOS專案的CLAUDE.md模式
您的CLAUDE.md是專案中最重要的agent輔助開發檔案。它是agent的入職文件,也就是讀過架構文件的新進工程師,和只能憑空猜測的新進工程師之間的差別。
我維護的每個iOS專案都有CLAUDE.md。以下是從全部8個app歸納出的有效模式。
必要章節
每個iOS CLAUDE.md都需要這6個章節。其他內容都是選配。
1. 專案身分
# Return - Zen Focus Timer
**Bundle ID:** `com.941apps.Return`
**Target:** iOS 26+ / macOS Tahoe / watchOS 26+ / tvOS 26+
**Architecture:** SwiftUI with @Observable pattern, companion Watch and TV apps
**Swift version:** 6.2
**Minimum deployment:** iOS 26.0
這為什麼重要:agent在撰寫任何程式碼前,必須知道部署目標。以iOS 17為目標的agent會使用NavigationView和@ObservedObject。以iOS 26為目標的agent則會使用NavigationStack和@Observable。Bundle ID會影響entitlements與HealthKit設定。Swift版本會決定並行模型(async/await相對於completion handlers,以及strict concurrency相對於lenient)。
2. 帶有用途註解的檔案結構
## File Structure
```
Return/
├── ReturnApp.swift # App entry, dark mode enforcement
├── ContentView.swift # Main timer view with theme backgrounds
├── TimerManager.swift # Timer state, logic, and repeat handling
├── AudioManager.swift # Sound playback with AVAudioPlayer
├── Settings.swift # Centralized settings with validation
├── SettingsSheet.swift # Settings UI
├── HealthKitManager.swift # Mindful session logging + cross-device sync
├── LiveActivityManager.swift # Lock Screen/Dynamic Island
├── Theme.swift # Theme definitions
├── ThemeManager.swift # Theme state management
├── VideoBackgroundView.swift # AVPlayer video backgrounds
├── GlassTextShape.swift # Core Text glyph paths for glass effect
├── GlassTimerText.swift # Timer text with glass material
└── Constants.swift # App constants
```
每個檔名後面的行內註解並非裝飾。這是您能撰寫的最高槓桿文件。當agent判斷新功能該加在哪裡時,這些註解會引導它第一次就找到正確檔案,而不是讀完每個檔案才理解專案配置。
反模式:只列檔案,不加註解。TimerManager.swift無法告訴agent它負責狀態、UI,或兩者皆是。TimerManager.swift # Timer state, logic, and repeat handling則清楚說明什麼該放在那裡,什麼不該放。
3. 建置與測試指令
## Build & Test
Build for iOS simulator:
```bash
xcodebuild -scheme Return -destination 'platform=iOS Simulator,name=iPhone 16 Pro' build
```
Run tests:
```bash
xcodebuild -scheme Return -destination 'platform=iOS Simulator,name=iPhone 16 Pro' test
```
Run tvOS tests:
```bash
xcodebuild -scheme ReturnTV -destination 'platform=tvOS Simulator,name=Apple TV' test
```
**Prefer MCP tools** (`build_sim`, `test_sim`) over these raw commands.
MCP returns structured JSON with categorized errors.
即使agent應優先使用MCP,仍要包含原始指令。原始指令可作為備援文件,並讓scheme名稱與destination一目了然。
4. 關鍵模式與規則
## Key Patterns
### Observable Architecture
- ALL view models use `@Observable` (NEVER `ObservableObject`)
- ALL navigation uses `NavigationStack` (NEVER `NavigationView`)
- State management via `@Observable` classes with `@MainActor` isolation
### Settings Pattern
- Centralized `Settings.shared` singleton
- All settings bounded to valid ranges with validation
- Sound names validated against whitelist
- Thread-safe access via @MainActor
### Audio System
- `AVAudioPlayer` with `.playback` category (plays in silent mode)
- Silent audio loop for background execution
- Bell playback with completion callbacks and token-based staleness
這些模式可防止agent引入不一致。若沒有明確的模式文件,agent有時會在某個檔案使用ObservableObject,另一個檔案使用@Observable;或是另外建立新的設定機制,而不是使用既有的Settings.sharedsingleton。
5. Agent絕對不可做的事
## Rules
- **NEVER modify .pbxproj files** — create Swift files, then I will add them to Xcode manually
- **NEVER modify .xcodeproj/ contents directly**
- **NEVER add new package dependencies** without asking first
- **NEVER change the deployment target**
- **NEVER modify entitlements files** unless explicitly asked
- **NEVER use NavigationView** — always NavigationStack
- **NEVER use ObservableObject** — always @Observable
- **NEVER use @StateObject** — always @State with @Observable
明確禁止比隱含期待更有效。agent遵守負向限制通常比正向建議更可靠,因為負向限制是二元的(做/不做),而不是啟發式的(優先使用這個/有時使用那個)。
6. 框架特定脈絡
此章節會依app而異。任何有非顯而易見設定的框架都應納入:
HealthKit apps:
## HealthKit Configuration
- Entitlement: `com.apple.developer.healthkit`
- Info.plist keys:
- `NSHealthShareUsageDescription`: "Return reads your mindful minutes..."
- `NSHealthUpdateUsageDescription`: "Return logs meditation sessions..."
- Category types: `HKCategoryType(.mindfulSession)`
- Authorization checked on every write (user can revoke at any time)
- HealthKit is unavailable on tvOS — guard with `#if canImport(HealthKit)`
SwiftData apps:
## SwiftData Models
### Model Relationships
- `GroceryList` has many `GroceryItem` (cascade delete)
- `GroceryItem` belongs to one `GroceryList`
- `GroceryItem` has optional `Category`
### Model Container Setup
- Configured in App struct with `modelContainer(for:)`
- Schema versioning: currently V2
- Migration plan: `GroceryMigrationPlan` handles V1 → V2
### Queries
- `@Query(sort: \GroceryItem.name)` for sorted fetches
- `@Query(filter: #Predicate { !$0.isCompleted })` for active items
- Always use `@Query` in views, `modelContext.fetch()` in managers
SpriteKit apps:
## SpriteKit Scene Hierarchy
```
GameScene (SKScene)
├── backgroundLayer (SKNode, zPosition: -100)
│ └── StarfieldNode (custom, parallax scrolling)
├── gameLayer (SKNode, zPosition: 0)
│ ├── playerShip (PlayerNode, zPosition: 10)
│ ├── enemyContainer (SKNode, zPosition: 5)
│ └── bulletPool (SKNode, zPosition: 8)
├── effectsLayer (SKNode, zPosition: 50)
│ └── ParticleManager (manages explosion/trail emitters)
└── hudLayer (SKNode, zPosition: 100)
├── scoreLabel (SKLabelNode)
└── healthBar (HealthBarNode)
```
- Physics categories defined in `PhysicsCategory.swift` as bitmasks
- Contact detection via `didBegin(_ contact:)` on GameScene
- Bullet pooling: pre-allocate 50, recycle via `removeFromParent()` + re-add
Metal apps:
## Metal Pipeline
- Render pipeline: `MetalView` → `Renderer` → `ShaderLibrary`
- Compute pipeline: `AudioAnalyzer` → compute shader → texture output
- Shared uniforms struct: `Uniforms` in `ShaderTypes.h` (bridged to Swift)
- Frame timing: `CADisplayLink` drives render loop
- Buffer triple-buffering: 3 in-flight frames with semaphore
### Shader Files
- `Shaders.metal` — Main render shaders (vertex + fragment)
- `Compute.metal` — Audio analysis compute kernel
- `PostProcess.metal` — Bloom and color grading
### DO NOT modify Metal shaders without testing on device.
Simulator Metal is not representative of device GPU behavior.
真實CLAUDE.md:Banana List(SwiftUI + SwiftData + iCloud + MCP Server)
以下是一個帶註解的範例,展示這6個章節如何在中等複雜度的app中相互搭配。這是我用於Banana List的CLAUDE.md模式;它是一個有53個檔案的購物清單app,具備iCloud同步,以及自訂MCPserver,可將app資料公開給ClaudeDesktop:
# Banana List - Grocery List App
**Bundle ID:** `com.941apps.BananaList`
**Target:** iOS 26+
**Architecture:** SwiftUI + SwiftData + iCloud Drive sync
**Swift version:** 6.2
**Minimum deployment:** iOS 26.0
## Core Features
- Grocery lists with items, categories, and quantities
- iCloud Drive sync via SwiftData CloudKit integration
- Custom MCP server exposing list data to Claude Desktop
- Liquid Glass design system
- Haptic feedback on interactions
- Share sheets for list sharing
## File Structure
```
BananaList/
├── BananaListApp.swift # App entry, model container setup
├── Models/
│ ├── GroceryList.swift # @Model: list with name, items, color
│ ├── GroceryItem.swift # @Model: item with name, quantity, category, isCompleted
│ ├── Category.swift # @Model: user-defined categories
│ └── SampleData.swift # Preview and test data
├── Views/
│ ├── ListsView.swift # Main list of grocery lists
│ ├── ListDetailView.swift # Items within a list
│ ├── ItemRow.swift # Single item row with swipe actions
│ ├── AddItemSheet.swift # New item form
│ ├── CategoryPicker.swift # Category selection with create-new
│ └── SettingsView.swift # App settings
├── Managers/
│ ├── CloudSyncManager.swift # iCloud Drive sync status and conflict resolution
│ └── HapticManager.swift # UIImpactFeedbackGenerator wrapper
├── MCP/
│ ├── MCPServer.swift # MCP server for Claude Desktop integration
│ ├── ListTools.swift # MCP tools: list CRUD operations
│ └── ItemTools.swift # MCP tools: item CRUD operations
└── Extensions/
├── Color+Extensions.swift # Custom color definitions
└── View+Extensions.swift # Reusable view modifiers
```
## SwiftData Models
### Relationships
- `GroceryList` has many `GroceryItem` (cascade delete)
- `GroceryItem` belongs to one `GroceryList` (required)
- `GroceryItem` has optional `Category`
- `Category` has many `GroceryItem` (nullify on delete)
### Container Setup
```swift
@main
struct BananaListApp: App {
var body: some Scene {
WindowGroup {
ListsView()
}
.modelContainer(for: [GroceryList.self, GroceryItem.self, Category.self])
}
}
```
### Query Patterns
- Lists: `@Query(sort: \GroceryList.name) var lists: [GroceryList]`
- Active items: `@Query(filter: #Predicate { !$0.isCompleted })`
- By category: filter in-memory after fetch (SwiftData predicate limitations)
## Build & Test
```bash
xcodebuild -scheme BananaList -destination 'platform=iOS Simulator,name=iPhone 16 Pro' build
xcodebuild -scheme BananaList -destination 'platform=iOS Simulator,name=iPhone 16 Pro' test
```
Prefer MCP tools (`build_sim`, `test_sim`) over raw commands.
## Key Patterns
### Observable + SwiftData
- SwiftData `@Model` classes are automatically Observable
- DO NOT add `@Observable` to `@Model` classes (redundant, causes warnings)
- Use `@Bindable` for two-way bindings to model properties in forms
- Use `@Query` in views, `modelContext.fetch()` in non-view code
### iCloud Sync
- Automatic via SwiftData CloudKit integration
- Conflict resolution: last-write-wins (CloudKit default)
- Sync status exposed via `CloudSyncManager.shared.syncState`
- Test sync by running on two simulators with same iCloud account
### MCP Server Architecture
- Runs as a local WebSocket server on port 8765
- Exposes 6 tools: listAll, getList, createList, addItem, completeItem, deleteItem
- Claude Desktop connects via MCP config in `~/.config/claude-desktop/config.json`
## Rules
- NEVER modify .pbxproj or .xcodeproj contents
- NEVER change the model schema without updating SampleData.swift
- NEVER use `ObservableObject` — SwiftData models are already Observable
- NEVER use `@StateObject` — use `@State` with `@Observable` classes
- NEVER use `NavigationView` — always `NavigationStack`
- NEVER add `@Observable` macro to `@Model` classes
- ALWAYS use `@Bindable` for form bindings to model properties
- ALWAYS test iCloud sync changes on two simulator instances
真實CLAUDE.md:Reps(極簡SwiftData App,14個檔案)
對小型專案而言,CLAUDE.md可以很精簡。以下是Reps這個14個檔案的健身訓練追蹤器模式。請注意,即使是簡短的CLAUDE.md,也涵蓋了全部6個必要章節:
# Reps - Workout Tracking
**Bundle ID:** `com.941apps.Reps`
**Target:** iOS 26+
**Architecture:** SwiftUI + SwiftData
**Swift version:** 6.2
## File Structure
```
Reps/
├── RepsApp.swift # App entry, model container
├── Models/
│ ├── Workout.swift # @Model: workout with exercises, date, duration
│ ├── Exercise.swift # @Model: exercise with sets, reps, weight
│ └── ExerciseTemplate.swift # @Model: saved exercise definitions
├── Views/
│ ├── WorkoutListView.swift # Main list of workouts
│ ├── WorkoutDetailView.swift # Exercises within a workout
│ ├── ExerciseRow.swift # Single exercise with inline editing
│ ├── AddExerciseSheet.swift # Exercise selection from templates
│ ├── NewWorkoutView.swift # Start new workout flow
│ └── StatsView.swift # Progress charts and summaries
├── Managers/
│ └── WorkoutTimer.swift # Active workout timer
└── Extensions/
└── Date+Extensions.swift # Formatting helpers
```
## Build & Test
```bash
xcodebuild -scheme Reps -destination 'platform=iOS Simulator,name=iPhone 16 Pro' build
xcodebuild -scheme Reps -destination 'platform=iOS Simulator,name=iPhone 16 Pro' test
```
## SwiftData Relationships
- `Workout` has many `Exercise` (cascade delete)
- `Exercise` has optional `ExerciseTemplate`
- `ExerciseTemplate` standalone (nullify on exercise delete)
## Rules
- NEVER modify .pbxproj
- NEVER use ObservableObject — use @Observable
- NEVER use NavigationView — use NavigationStack
- @Model classes are already Observable — do not add @Observable macro
- Use @Bindable for form bindings to model properties
這是一個14個檔案專案的40行CLAUDE.md。只需10分鐘撰寫,卻能省下數小時的agent困惑。
真實CLAUDE.md:Starfield Destroyer(SpriteKit + Metal,32個檔案)
遊戲專案需要更多框架特定脈絡。agent必須理解場景圖、physics categories,以及遊戲狀態機:
# Starfield Destroyer - Space Shooter
**Bundle ID:** `com.941apps.StarfieldDestroyer`
**Target:** iOS 26+
**Architecture:** SpriteKit + Metal post-processing + Game Center
**Swift version:** 6.2
## Game Overview
99 levels across 3 galaxies. 8 unlockable ships with different stats.
Game Center leaderboards and achievements. Metal shader post-processing
for bloom and screen effects.
## File Structure
```
StarfieldDestroyer/
├── StarfieldDestroyerApp.swift # App entry, Game Center auth
├── GameScene.swift # Main game scene, update loop
├── MenuScene.swift # Title screen, ship selection
├── Entities/
│ ├── PlayerShip.swift # Player node with physics, weapons, shields
│ ├── EnemyShip.swift # Enemy base class with AI behaviors
│ ├── Bullet.swift # Bullet pool node
│ ├── PowerUp.swift # Collectible power-ups
│ └── Boss.swift # Boss enemies (levels 33, 66, 99)
├── Systems/
│ ├── LevelManager.swift # Level progression, wave spawning
│ ├── PhysicsCategory.swift # UInt32 bitmask categories
│ ├── CollisionHandler.swift # Contact delegate methods
│ ├── ScoreManager.swift # Score tracking, multipliers
│ ├── ParticleManager.swift # Explosion, trail, shield emitters
│ └── AudioManager.swift # Sound effects, background music
├── UI/
│ ├── HUDNode.swift # Score, health, level display
│ ├── ShipSelectView.swift # SwiftUI ship selection (UIHostingController)
│ ├── GameOverView.swift # Game over screen with score submission
│ └── PauseMenu.swift # Pause overlay
├── Metal/
│ ├── MetalRenderer.swift # Post-processing render pipeline
│ ├── BloomShader.metal # Bloom post-process effect
│ └── ShaderTypes.h # Shared uniforms (bridging header)
├── Data/
│ ├── ShipData.swift # 8 ship definitions (speed, damage, shields)
│ ├── LevelData.swift # 99 level configurations
│ └── AchievementData.swift # Game Center achievement definitions
└── GameCenterManager.swift # Leaderboard/achievement submission
```
## SpriteKit Scene Hierarchy
```
GameScene (SKScene)
├── backgroundLayer (zPosition: -100)
│ └── StarfieldNode (parallax scrolling, 3 layers)
├── gameLayer (zPosition: 0)
│ ├── playerShip (zPosition: 10)
│ ├── enemyContainer (zPosition: 5)
│ ├── bulletPool (zPosition: 8) — pre-allocated 50 bullets
│ └── powerUpContainer (zPosition: 3)
├── effectsLayer (zPosition: 50)
│ └── ParticleManager (explosion + trail emitters)
└── hudLayer (zPosition: 100)
├── scoreLabel (SKLabelNode)
├── healthBar (custom SKShapeNode)
└── levelLabel (SKLabelNode)
```
## Physics Categories
```swift
struct PhysicsCategory {
static let none: UInt32 = 0
static let player: UInt32 = 0b1 // 1
static let enemy: UInt32 = 0b10 // 2
static let bullet: UInt32 = 0b100 // 4
static let powerUp: UInt32 = 0b1000 // 8
static let shield: UInt32 = 0b10000 // 16
static let bossBullet:UInt32 = 0b100000 // 32
}
// Contact pairs:
// player + enemy → damage
// player + powerUp → collect
// bullet + enemy → destroy
// player + bossBullet → damage
```
## Game State Machine
```
.menu → .playing → .paused → .playing
→ .gameOver → .menu
→ .bossIntro → .playing
→ .levelComplete → .playing (next level)
```
## Metal Post-Processing
- Bloom shader: `BloomShader.metal` — multi-pass Gaussian blur + additive blend
- Uniforms: `PostProcessUniforms { float intensity; float threshold; float2 resolution; }`
- Applied after SpriteKit renders each frame via `SKView.presentScene(:transition:)`
- DO NOT modify Metal shaders without testing on device
## Build & Test
```bash
xcodebuild -scheme StarfieldDestroyer -destination 'platform=iOS Simulator,name=iPhone 16 Pro' build
xcodebuild -scheme StarfieldDestroyer -destination 'platform=iOS Simulator,name=iPhone 16 Pro' test
```
## Rules
- NEVER modify .pbxproj
- NEVER modify PhysicsCategory bitmasks (breaks all collision detection)
- NEVER change the scene hierarchy z-ordering without understanding render order
- NEVER modify ShaderTypes.h without updating both Swift and Metal references
- Add new enemies by subclassing EnemyShip, not by modifying it
- Bullet pooling: recycle via removeFromParent() + re-add, never allocate new
- Game Center: always check isAuthenticated before submitting scores
真實CLAUDE.md:amp97(Metal + 音訊視覺化,41個檔案)
Metal專案最需要框架特定脈絡,因為agent無法驗證視覺輸出:
# amp97 - Audio Visualizer
**Bundle ID:** `com.941apps.amp97`
**Target:** iOS 26+
**Architecture:** Metal render pipeline + AVAudioEngine analysis
**Swift version:** 6.2
## Architecture
```
Audio Input (microphone/file)
→ AVAudioEngine tap
→ FFT (vDSP)
→ Frequency/amplitude buffers
→ Metal compute shader (analysis)
→ Metal render pipeline (visualization)
→ CADisplayLink (60fps)
→ MTKView
```
## File Structure
```
amp97/
├── amp97App.swift # App entry
├── Audio/
│ ├── AudioEngine.swift # AVAudioEngine setup, tap installation
│ ├── FFTProcessor.swift # vDSP FFT, frequency bin extraction
│ ├── AudioBuffer.swift # Ring buffer for audio data
│ └── MicrophoneManager.swift # Microphone permission, session config
├── Rendering/
│ ├── MetalView.swift # MTKView wrapper for SwiftUI
│ ├── Renderer.swift # Main render loop, pipeline state
│ ├── ShaderLibrary.swift # Compiled shader management
│ ├── BufferManager.swift # Triple-buffered uniform updates
│ └── TextureManager.swift # Offscreen render targets
├── Shaders/
│ ├── Shaders.metal # Vertex + fragment shaders
│ ├── AudioCompute.metal # Audio analysis compute kernel
│ ├── PostProcess.metal # Bloom, color grading
│ └── ShaderTypes.h # Shared uniforms (bridging header)
├── Visualizations/
│ ├── WaveformViz.swift # Oscilloscope-style waveform
│ ├── SpectrumViz.swift # Frequency spectrum bars
│ ├── CircularViz.swift # Radial visualization
│ └── VizSelector.swift # Visualization switching
├── Views/
│ ├── MainView.swift # Full-screen viz with overlays
│ ├── ControlsOverlay.swift # Play/pause, viz selection, gain
│ └── SettingsView.swift # Audio source, sensitivity
└── Extensions/
├── SIMD+Extensions.swift # Vector math helpers
└── Color+Metal.swift # UIColor → float4 conversion
```
## Metal Pipeline
### Uniforms (ShaderTypes.h)
```c
typedef struct {
float time;
float2 resolution;
float audioLevel; // 0.0-1.0 RMS amplitude
float frequencyBins[64]; // FFT output, normalized
float4x4 transform;
} Uniforms;
```
### Render Pipeline
1. Compute pass: AudioCompute.metal processes FFT data → texture
2. Render pass: Shaders.metal reads texture + uniforms → visualization
3. Post-process pass: PostProcess.metal applies bloom → final output
### Buffer Management
- Triple buffering with DispatchSemaphore(value: 3)
- Uniforms updated per-frame on CPU, consumed by GPU 1-2 frames later
- Audio data ring buffer: 4096 samples, lock-free single producer/consumer
## Rules
- NEVER modify ShaderTypes.h without updating BOTH Swift and Metal sides
- NEVER exceed 64 frequency bins (fixed buffer size in shader)
- NEVER test Metal visual output in simulator — device only
- NEVER modify the audio engine tap format (48kHz, mono, float32)
- Triple buffer discipline: always signal semaphore in completion handler
- Audio session: .playAndRecord category with .defaultToSpeaker option
依專案規模擴充CLAUDE.md
合適的詳細程度取決於檔案數量與框架複雜度:
| 專案規模 | CLAUDE.md深度 | 範例 |
|---|---|---|
| 小型(<20個檔案) | 身分+檔案清單+規則 | Reps(14個檔案):基本SwiftData模式、建置指令、禁止事項 |
| 中型(20-40個檔案) | +框架脈絡+關鍵模式 | TappyColor(30個檔案):SpriteKit場景階層、physics categories、game loop |
| 大型(40個以上檔案) | +架構圖+關係圖+多target資訊 | Return(63個檔案):跨平台架構、session同步圖、各平台差異 |
| 專門領域(Metal/GPU) | +pipeline圖+共用型別定義+buffer layout | amp97(41個檔案):render pipeline階段、uniform struct、buffer管理 |
過度文件化的成本幾乎為零(agent會略過不需要的內容)。文件不足的成本則很高(agent會自行創造與您程式碼庫衝突的模式)。
CLAUDE.md檢查清單
建立或稽核iOS專案的CLAUDE.md時,請使用這份檢查清單:
- [ ] 已指定Bundle ID與部署目標
- [ ] 已標明Swift版本與架構模式
- [ ] 檔案結構含行內用途註解
- [ ] 建置指令含正確scheme與destination
- [ ] 測試指令含正確scheme與destination
- [ ] 已註明MCP偏好(「prefer build_sim over xcodebuild」)
- [ ] @Observable規則(絕不使用ObservableObject)
- [ ] NavigationStack規則(絕不使用NavigationView)
- [ ] .pbxproj禁止事項
- [ ] 框架特定脈絡(HealthKit權限、SwiftData關係、SpriteKit階層、Metal pipeline)
- [ ] 已記錄平台可用性guard(#if canImport、#if os)
- [ ] 已記錄關鍵singleton與共用模式
- [ ] 已註明已知限制或注意事項
您的第一個代理程式工作階段
在專案中設定好MCP並放入CLAUDE.md後,以下是一次有效初始工作階段的流程示範。此處使用Claude Code CLI,但此工作流程適用於任何執行階段。
步驟1:確認代理程式能看見您的專案
You: Summarize this project. What scheme should I build with?
Claude: [reads CLAUDE.md]
[calls discover_projs via MCP]
[calls list_schemes via MCP]
This is Return, a zen meditation timer for iOS 26+, watchOS, and tvOS.
Available schemes: Return, ReturnWatch, ReturnTV, ReturnTests.
Primary scheme for iOS: Return.
如果代理程式沒有引用您的CLAUDE.md內容,請確認該檔案位於專案根目錄(也就是與.xcodeproj或Package.swift相同的目錄)。
步驟2:執行健康檢查建置
You: Build the Return scheme for iOS simulator and report results.
Claude: [calls list_sims — finds iPhone 16 Pro on iOS 26.2]
[calls boot_sim — boots the simulator]
[calls build_sim — builds the project]
Build succeeded. 63 source files compiled.
2 warnings:
- HomeView.swift:132 — UIScreen.main deprecated in iOS 26.0
- LogWaterIntent.swift:61 — Result of try? is unused
0 errors.
步驟3:執行測試
You: Run all tests and report pass/fail.
Claude: [calls test_sim]
12 tests executed:
✓ TimerManagerTests (5/5 passed)
✓ SettingsTests (4/4 passed)
✓ ConstantsTests (3/3 passed)
All tests passed.
步驟4:實作功能
You: Add a new "Rain" theme to the theme system. Follow the existing
pattern in Theme.swift and ThemeManager.swift. Include a rain
ambient sound. Build and test after implementation.
Claude: [reads Theme.swift — understands Theme struct pattern]
[reads ThemeManager.swift — understands theme registration]
[reads existing theme definitions]
[adds Rain theme to Theme.swift following existing pattern]
[registers Rain theme in ThemeManager.swift]
[calls build_sim — build succeeds]
[calls test_sim — all tests pass]
Added Rain theme:
- Theme.swift: new `static let rain` with video, cover, ambient
- ThemeManager.swift: added to `allThemes` array
- Build: success (0 errors, 2 existing warnings)
- Tests: 12/12 passed
Note: You'll need to add rain_ambient.wav to the project
and add the new Theme.swift changes to the Xcode target manually
(I did not modify .pbxproj).
代理程式提到不要修改.pbxproj,是因為CLAUDE.md中的規則。若沒有這條規則,代理程式會嘗試修改專案檔案,而且很可能造成損毀。
代理程式在iOS中擅長的工作
以下是代理程式能穩定產出正確、可投入生產環境成果的工作類型,通常只需要極少人工審查。
SwiftUI Views與Modifiers
代理程式對SwiftUI宣告式語法具備深度模式辨識能力。View組合、modifier鏈、狀態繫結與版面配置,都很適合代理程式的訓練資料,因為SwiftUI的API介面有完整文件,且模式高度一致。
代理程式擅長的項目:
- 根據描述建立新的views(「建立一個settings sheet,包含X、Y、Z的toggles」)
- 套用modifier鏈(.glassEffect()、.sensoryFeedback()、.navigationTitle())
- 在版面配置模式之間轉換(VStack轉為LazyVGrid、List轉為ScrollView)
- 實作@Bindable表單繫結到SwiftData models
- 使用範例資料建立preview providers
能產出優異結果的範例提示:
Create a SettingsView that matches the existing pattern in SettingsSheet.swift.
Include toggles for:
- Enable haptic feedback (Settings.shared.hapticsEnabled)
- Enable HealthKit logging (Settings.shared.healthKitEnabled)
- Show session history (navigation link to SessionHistoryView)
Use Liquid Glass styling with .glassEffect() on section backgrounds.
Follow the @Observable pattern, not ObservableObject.
具體程度很重要。「Create a settings view」會產生泛用結果。「Create a SettingsView that matches the existing pattern in SettingsSheet.swift」則會產生與您的程式碼庫一致的輸出。
SwiftData Models與Queries
代理程式能可靠處理SwiftData的@Modelmacro、relationships與@Query模式。此框架的宣告式特性(類似Django ORM或SQLAlchemy)很容易對應到代理程式在許多程式碼庫中看過的模式。
代理程式擅長的項目:
- 定義含有relationships的@Modelclasses
- 使用sort descriptors與predicates撰寫@Query
- 透過modelContext實作CRUD操作
- 規劃schema版本之間的migration
- 建立preview資料與test fixtures
代理程式需要指引的項目:
- 複雜的#Predicateexpressions(SwiftData的predicate DSL有限制,代理程式不一定總是知道;建議在CLAUDE.md中記錄已知限制)
- CloudKit同步設定(可由SwiftData自動處理,但代理程式可能會嘗試實作手動同步)
Unit Tests
代理程式為iOS專案撰寫的unit tests一向品質很高。代理程式理解XCTest模式、async測試方法,以及setup/teardown生命週期。
Write unit tests for TimerManager covering:
1. Initial state is .stopped
2. start() transitions to .running
3. pause() transitions to .paused
4. reset() returns to .stopped with original duration
5. Timer counts down correctly (test with 3-second duration)
代理程式會產出結構良好的XCTest案例,包含setUp()與tearDown()、適當的assertions,以及針對timer-based tests的async處理。
重構與模式套用
代理程式擅長機械式重構:將views抽出成components、將ObservableObject轉換為@Observable、從NavigationView遷移到NavigationStack,並在多個檔案中套用一致模式。
Refactor all views in the Views/ directory to use @Observable instead of
ObservableObject. Update @StateObject to @State, @ObservedObject to direct
property access, and @Published to plain properties.
代理程式會有條不紊地逐一處理每個檔案,正確套用轉換,並維持既有功能。這是高槓桿工作:原本需要1小時手動編輯的重構,能在數分鐘內以近乎完美的準確度完成。
透過MCP診斷建置錯誤
有了結構化的MCP輸出,代理程式診斷建置錯誤的速度比大多數開發者更快。代理程式會讀取錯誤JSON、找出確切檔案與行號、理解錯誤訊息,並套用修正;通常一輪就能完成。
代理程式可自主修復的錯誤: - 缺少imports - 型別不相符 - Protocol conformance缺口 - 已棄用的API用法(並替換為新寫法) - 缺少必要的initializer參數 - 存取控制違規
代理程式需要協助的錯誤: - 模稜兩可的型別解析(多個modules定義了相同型別) - 複雜的generic constraint失敗 - Macro expansion錯誤(代理程式無法看見展開後的macro輸出)
Simulator管理
代理程式能透過MCP妥善處理simulator生命週期:
Boot an iPhone 16 Pro simulator on iOS 26, install the app, and take a screenshot.
代理程式會呼叫list_sims尋找可用的runtimes,呼叫boot_sim啟動simulator,呼叫build_sim進行建置與安裝,並呼叫screenshot擷取畫面;全部都透過結構化的MCP呼叫完成。
Agent在iOS中表現不佳的地方
誠實盤點agent容易失敗之處。了解這些界線,才能避免挫折與浪費tokens。
.pbxproj檔案修改——絕對不要
這是iOS agent開發中最重要的一條規則。.pbxproj檔案是Xcode的專案設定,也就是一個結構化文字檔,包含UUID參照、建置階段清單與target成員資格。名義上可供人類閱讀,但對AI agents而言,實務上幾乎無法解析。
為什麼agent會在.pbxproj失敗: - 這個檔案使用自訂格式(不是JSON、不是YAML、也不是XML),而且位置具有意義 - 每個項目都透過UUID交叉參照;新增一個檔案需要一致地更新3到5個不同區段 - 只要一個字元放錯位置,就會毀損整個專案檔案 - Xcode對.pbxproj的merge conflict解析本來就很脆弱;agent編輯只會讓情況更糟
當agent編輯.pbxproj時會發生什麼: 1. 編輯看似成功(agent回報「檔案已更新」) 2. Xcode拒絕開啟專案(「專案檔案已毀損」) 3. 您花15到60分鐘從git歷史中復原 4. 您學會加入PreToolUse hook(請參閱Hooks)
工作流程:agent建立Swift檔案。您手動將它們加入Xcode專案(拖進Xcode,或使用File > Add Files)。每個檔案只要5秒,卻能避免數小時的復原工作。
對Swift Package Manager專案而言:這項限制較不嚴重。Package.swift是標準Swift檔案,agent可以可靠地編輯。如果您的專案只使用SPM(沒有.xcodeproj),agent就能管理完整的專案結構。
複雜的Interface Builder/Storyboard編輯
如果您的專案使用Interface Builder(.xib檔案)或Storyboards(.storyboard檔案),agent無法有意義地編輯它們。這些是XML檔案,包含自動產生的UUID、constraint參照與outlet連線,設計目的在於視覺化編輯,而不是文字編輯。
緩解方式:新view一律使用SwiftUI。如果專案中有舊版Interface Builder檔案,保持原狀,並用SwiftUI建置新的UI。
效能最佳化
Agent會寫出正確的程式碼,但不一定是高效能的程式碼。它們無法profile您的app、找出瓶頸,或測量影格率。效能最佳化需要:
- Instruments profiling(視覺化工具,agent無法存取)
- 理解特定裝置的GPU/CPU特性
- 以測量為依據,反覆調整
常見情境: - Metal shader最佳化(agent會寫出有效的Metal,但無法測量GPU影格時間) - SwiftUI view body複雜度(agent會建立深度巢狀view,造成重繪負擔) - Core Data/SwiftData fetch最佳化(agent會寫出正確查詢,但在大型資料集上可能很慢)
緩解方式:用agent進行實作,手動透過Instruments profile,然後請agent套用您已確認的特定最佳化。
Code Signing與Provisioning
除了讀取錯誤訊息之外,agent無法偵錯code signing問題。Provisioning profile管理、憑證建立、entitlement設定與App Store提交,本質上都是由人操作的工作流程,牽涉Apple Developer portal、Keychain Access,以及Xcode的signing UI。
agent看得到什麼:「Signing for ‘Return’ requires a development team.」
agent看不到什麼:您的憑證是否過期、provisioning profile是否包含該裝置、bundle ID是否符合App ID,或entitlements檔案是否正確。
緩解方式:所有signing都在Xcode的Signing & Capabilities分頁處理。不要要求agent偵錯signing失敗。
複雜的Metal Shader偵錯
Agent會寫出語法正確的Metal Shading Language(MSL),但無法驗證視覺輸出,也無法偵錯GPU端問題。Metal shaders在GPU上執行;agent沒有回饋機制能判斷shader是否產生正確的視覺結果。
agent可以用Metal做什麼:
- 根據描述撰寫vertex與fragment shaders
- 在Swift中設定Metal render pipeline
- 為資料平行運算建立compute shaders
- 修正.metal檔案中的編譯錯誤
agent無法用Metal做什麼: - 驗證shader輸出的視覺正確性 - 偵錯GPU效能(影格時間、occupancy、記憶體頻寬) - 診斷視覺瑕疵(banding、精度問題、錯誤色彩空間) - 在不同GPU架構上測試(A-series與M-series的行為差異)
緩解方式:在實體裝置上測試Metal shaders。Simulator的Metal實作無法代表裝置上的GPU行為。使用Xcode的GPU Frame Capture進行視覺偵錯。
視覺版面驗證
Agent看不到app的UI。它們會撰寫SwiftUI版面程式碼,也能確認程式碼可編譯,但無法判斷結果畫面是否正確。某個view如果偏離中心10像素、字重錯誤,或元素互相重疊,不會產生build error,也會通過所有邏輯測試。
緩解方式:以視覺方式檢查UI變更。使用Xcode中的SwiftUI Previews(或透過Apple MCP使用RenderPreview進行headless rendering)驗證版面。也可以考慮使用swift-snapshot-testing等函式庫進行snapshot testing,以自動偵測視覺回歸。
iOS 開發專用 Hooks
Hooks 是在代理工作流程中特定節點必然執行的 shell 指令。它們是規則的強制執行機制——「請勿編輯 .pbxproj」只是代理可能忽略的建議,而「您無法編輯 .pbxproj」則是強制封鎖。
如需瞭解 hook 系統的背景資訊,請參閱 Claude Code hooks 指南。本節將介紹 iOS 專用的 hook 模式。
PreToolUse:封鎖寫入 .pbxproj
這是所有 iOS 專案中最重要的 hook。它會禁止代理寫入 .pbxproj 檔案、.xcodeproj/ 目錄及其他由 Xcode 管理的檔案:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"command": "bash -c 'INPUT=$(cat); FP=$(echo \"$INPUT\" | jq -r \".tool_input.file_path // empty\"); if echo \"$FP\" | grep -qE \"\\.(pbxproj|xcworkspace|xib|storyboard)$|xcodeproj/|xcworkspace/\"; then echo \"BLOCKED: Do not modify Xcode project files. Create Swift files and add to Xcode manually.\" >&2; exit 2; fi'"
}
]
}
}
請將此設定放在專案根目錄的 .claude/settings.json 中,或放在 ~/.claude/settings.json 中以提供全域保護。
運作方式:代理嘗試使用 Edit 或 Write 工具處理任何符合模式的檔案時,hook 便會執行、偵測檔案路徑、將警告輸出至 stderr,並以狀態碼 2 結束(藉此封鎖工具的使用)。代理收到錯誤訊息後,會調整處理方式。
可攔截的項目:
- 直接編輯 .pbxproj
- .xcodeproj/ 或 .xcworkspace/ 目錄內的任何檔案
- Interface Builder 檔案(.xib、.storyboard)
PostToolUse:使用 SwiftFormat 儲存時自動格式化
代理每次寫入或編輯 Swift 檔案時,自動進行格式化:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"command": "bash -c 'INPUT=$(cat); FP=$(echo \"$INPUT\" | jq -r \".tool_input.file_path // empty\"); if echo \"$FP\" | grep -qE \"\\.swift$\"; then swiftformat \"$FP\" --quiet 2>/dev/null; fi'"
}
]
}
}
必要條件:必須安裝 SwiftFormat(brew install swiftformat)。
這為何重要:代理產生的 Swift 雖然語法正確,卻不一定會始終遵循格式慣例。SwiftFormat 可統一縮排、大括號位置及 import 排序。8 透過儲存時自動格式化的 hook,代理接觸過的每個 Swift 檔案都會在您看到之前自動完成格式化。
選用:在專案根目錄新增 .swiftformat 設定檔,以自訂格式化規則:
# .swiftformat
--indent 4
--allman false
--stripunusedargs closure-only
--importgrouping testable-bottom
--header strip
PostToolUse:自動執行 SwiftLint
如果您使用 SwiftLint,請在每次編輯 Swift 檔案後執行:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"command": "bash -c 'INPUT=$(cat); FP=$(echo \"$INPUT\" | jq -r \".tool_input.file_path // empty\"); if echo \"$FP\" | grep -qE \"\\.swift$\"; then swiftlint lint --path \"$FP\" --quiet 2>/dev/null || true; fi'"
}
]
}
}
|| true 可避免 lint 警告封鎖代理。若希望 lint 違規項目造成封鎖,請將其移除。
PostToolUse:變更後自動建置
若要建立更積極的回饋迴圈,可在每次變更 Swift 檔案後觸發建置:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"command": "bash -c 'INPUT=$(cat); FP=$(echo \"$INPUT\" | jq -r \".tool_input.file_path // empty\"); if echo \"$FP\" | grep -qE \"\\.swift$\"; then xcodebuild -scheme Return -destination \"platform=iOS Simulator,name=iPhone 16 Pro\" build 2>&1 | tail -5; fi'"
}
]
}
}
警告:此做法成本高昂。每次編輯檔案都會觸發建置,請審慎使用——最適合需要立即取得建置回饋的偵錯階段。一般開發時,請讓代理準備就緒後,再透過 MCP 手動觸發建置。
PreToolUse:封鎖修改 Entitlements
保護 Entitlements 檔案,避免代理意外修改:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"command": "bash -c 'INPUT=$(cat); FP=$(echo \"$INPUT\" | jq -r \".tool_input.file_path // empty\"); if echo \"$FP\" | grep -qE \"\\.entitlements$\"; then echo \"BLOCKED: Do not modify entitlements files without explicit permission.\" >&2; exit 2; fi'"
}
]
}
}
整合式 iOS Hook 設定
以下是我在所有 iOS 專案中使用的完整 .claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"command": "bash -c 'INPUT=$(cat); FP=$(echo \"$INPUT\" | jq -r \".tool_input.file_path // empty\"); if echo \"$FP\" | grep -qE \"\\.(pbxproj|xcworkspace|xib|storyboard|entitlements)$|xcodeproj/|xcworkspace/\"; then echo \"BLOCKED: Do not modify Xcode-managed files. Create Swift files and add manually.\" >&2; exit 2; fi'"
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"command": "bash -c 'INPUT=$(cat); FP=$(echo \"$INPUT\" | jq -r \".tool_input.file_path // empty\"); if echo \"$FP\" | grep -qE \"\\.swift$\"; then swiftformat \"$FP\" --quiet 2>/dev/null; fi'"
}
]
}
}
此設定提供兩項保證: 1. 代理無法破壞 Xcode 專案檔案(PreToolUse 封鎖) 2. 代理接觸的每個 Swift 檔案都會自動格式化(PostToolUse 格式化)
適合與代理協作的架構模式
並非所有Swift架構都同樣適合代理。以下模式明確、一致,且在訓練資料中有充分範例,因此能產生最佳成果。
@Observable(不使用ObservableObject)
以iOS 26+為目標的平台應一律使用@Observable。這不僅是現代化模式,也最適合代理:
// CORRECT — @Observable
@Observable
@MainActor
final class TimerManager {
var timeRemaining: TimeInterval = 0
var state: TimerState = .stopped
func start() {
state = .running
// ...
}
}
// In a view:
struct TimerView: View {
@State private var timer = TimerManager()
var body: some View {
Text(timer.timeRemaining, format: .number)
}
}
// WRONG — ObservableObject (deprecated pattern)
class TimerManager: ObservableObject {
@Published var timeRemaining: TimeInterval = 0
@Published var state: TimerState = .stopped
}
// WRONG — @StateObject (deprecated pattern)
struct TimerView: View {
@StateObject private var timer = TimerManager()
}
為何@Observable適合代理:此模式更為簡潔(不需要@Published註解),所有權模型也更清楚(使用@State,無須在@StateObject與@ObservedObject之間選擇)。由於涉及的元件較少,代理使用此模式時也較不容易產生錯誤。
請在CLAUDE.md中記錄此規範:即使目標平台是iOS 26,代理偶爾仍會依據訓練資料,退回使用ObservableObject模式。明文禁止即可防止此情況。
NavigationStack(不使用NavigationView)
// CORRECT
NavigationStack {
List(items) { item in
NavigationLink(value: item) {
ItemRow(item: item)
}
}
.navigationDestination(for: Item.self) { item in
ItemDetailView(item: item)
}
}
// WRONG
NavigationView {
List(items) { item in
NavigationLink(destination: ItemDetailView(item: item)) {
ItemRow(item: item)
}
}
}
NavigationStack適用於iOS 16+,也是新程式碼唯一應採用的導覽模式。型別安全的navigationDestination(for:)模式可避免代理建立錯誤的導覽連結。
使用SwiftData進行持久化
在代理輔助開發中,SwiftData模型是最簡潔的持久化模式:
@Model
final class GroceryItem {
var name: String
var quantity: Int
var isCompleted: Bool
var category: Category?
var list: GroceryList?
init(name: String, quantity: Int = 1) {
self.name = name
self.quantity = quantity
self.isCompleted = false
}
}
代理使用SwiftData時的重要規則:
1. @Model類別會自動成為Observable——請勿加入@Observable
2. 表單繫結請使用@Bindable:@Bindable var item: GroceryItem
3. 在檢視中使用@Query取得響應式資料:@Query var items: [GroceryItem]
4. 在非檢視程式碼中使用modelContext.fetch()
5. 刪除關聯時必須明確指定規則:.cascade、.nullify、.deny
Swift 6.2並行處理
新專案應以Swift 6.2嚴格並行處理為目標。這是語言模式的選擇,而非工具鏈版本限制——穩定版Xcode 26.6中的Swift 6.3編譯器,以及Xcode 27測試版中的Swift 6.4,都能原封不動地建置這些模式:1718
// Actor isolation for shared mutable state
@MainActor
@Observable
final class DataManager {
var items: [Item] = []
func loadItems() async throws {
let fetched = try await api.fetchItems()
items = fetched // Safe: @MainActor isolated
}
}
// Sendable conformance for cross-actor transfers
struct Item: Sendable, Identifiable {
let id: UUID
let name: String
let createdAt: Date
}
代理的並行處理指引:
- 將所有檢視模型標記為@MainActor(避免資料競爭警告)
- 所有非同步工作都使用async/await(不使用完成處理常式)
- 跨actor傳遞的值型別應符合Sendable
- 在檢視中使用Task { }進行非同步初始化
- 只有在量測後確認有實際效能需求時,才使用nonisolated
Liquid Glass設計系統(iOS 26+)
iOS 26導入了Liquid Glass設計系統。只要提供明確指引,代理便能妥善運用:
// Glass effect on containers
VStack {
// content
}
.glassEffect()
// Glass effect with tint
Button("Action") { }
.glassEffect(.regular.tint(.blue))
// Glass effect on navigation bars (automatic in iOS 26)
NavigationStack {
// content
}
// Navigation bar automatically uses glass material
// Custom glass shapes
RoundedRectangle(cornerRadius: 16)
.fill(.ultraThinMaterial)
.glassEffect()
請納入CLAUDE.md:「在區段背景與卡片容器上使用.glassEffect()。導覽列會在iOS 26中自動採用玻璃材質。請勿使用自訂材質手動重現玻璃效果,應使用系統修飾器。」
特定框架的背景資訊
每個Apple框架都有代理需要特別留意的事項。本節涵蓋這8款App所使用的框架。
HealthKit
使用此框架的App:Return、Water
HealthKit需要審慎處理權限與平台條件檢查:
// Always check availability and authorization
import HealthKit
@MainActor
@Observable
final class HealthKitManager {
private let store = HKHealthStore()
var isAuthorized = false
func requestAuthorization() async {
guard HKHealthStore.isHealthDataAvailable() else { return }
let types: Set<HKSampleType> = [
HKQuantityType(.dietaryWater),
HKCategoryType(.mindfulSession)
]
do {
try await store.requestAuthorization(toShare: types, read: types)
isAuthorized = true
} catch {
// User denied — do not retry automatically
}
}
}
代理使用HealthKit時的規則:
- 一律使用HKHealthStore.isHealthDataAvailable()進行條件檢查
- 切勿假設已獲授權——每次寫入前都要檢查
- 多平台程式碼應使用#if canImport(HealthKit)(tvOS不支援HealthKit)
- 除HealthKit提供的資料外,切勿在本機儲存健康資料
- 在Info.plist中同時加入NSHealthShareUsageDescription與NSHealthUpdateUsageDescription
SpriteKit
使用此框架的App:TappyColor、Starfield Destroyer
SpriteKit的場景圖模型需要明確的代理指引:
## SpriteKit Rules
- Scene hierarchy is a tree of SKNodes with zPosition ordering
- Physics bodies use category bitmasks (UInt32) for collision detection
- Node pooling: pre-allocate reusable nodes (bullets, particles)
- Never add nodes directly to the scene — use layer nodes for organization
- Update loop: `update(_ currentTime:)` runs every frame — keep it fast
- Actions: use SKAction sequences for animations, not manual property updates
- Textures: use texture atlases for performance (.atlas directories)
代理使用SpriteKit時的強項: - 建立SKAction序列與群組 - 設定物理實體與接觸偵測 - 實作遊戲狀態機 - 建立HUD覆疊介面
代理使用SpriteKit時的弱項: - 對效能敏感的遊戲迴圈(代理會在每一影格加入不必要的工作) - 複雜的物理模擬(若要求精準度,自訂物理系統優於SKPhysicsBody) - 粒子效果調校(涉及視覺判斷,需要反覆調整)
Metal
使用此框架的App:amp97、Water、Starfield Destroyer
Metal是代理最難掌握的框架。GPU程式設計模型與CPU端Swift截然不同,代理也無法驗證視覺輸出。
## Metal Rules
- Shared types between Swift and Metal go in a bridging header (ShaderTypes.h)
- Triple buffer in-flight frames (semaphore with value 3)
- Test shaders on DEVICE, not simulator (Metal behavior differs)
- Compute shaders: threadgroup size must divide evenly into grid size
- Fragment shaders: output color must be in correct color space (sRGB or linear)
- DO NOT optimize shaders without Instruments GPU profiling data
Metal專案的CLAUDE.md應包含: - Uniforms結構定義(由Swift與MSL共用) - 算繪管線狀態的設定模式 - 緩衝區索引及其用途 - 現有著色器及各自的功能 - 已知的精確度問題(half與float的差異)
Live Activities
使用此框架的App:Return
Live Activities需要特定設定。只要完成記錄,代理便能妥善處理:
## Live Activities
- ActivityAttributes defined in `TimerActivityAttributes.swift`
- ActivityKit framework: `import ActivityKit`
- Widget extension: `ReturnWidgets/ReturnLiveActivity.swift`
- Start: `Activity<TimerActivityAttributes>.request(attributes:content:)`
- Update: `activity.update(ActivityContent(state:staleDate:))`
- End: `activity.end(ActivityContent(state:staleDate:), dismissalPolicy:)`
- Push token: register for updates via `activity.pushTokenUpdates`
Game Center
使用此框架的App:Starfield Destroyer
## Game Center
- Authentication: `GKLocalPlayer.local.authenticateHandler`
- Leaderboards: `GKLeaderboard.submitScore(_:context:player:leaderboardIDs:completionHandler:)`
- Achievements: `GKAchievement.report(_:withCompletionHandler:)` (takes `[GKAchievement]` array)
- Always check `GKLocalPlayer.local.isAuthenticated` before submitting
- Handle authentication failure gracefully (offline play must work)
多平台模式
Return橫跨iOS、watchOS與tvOS。使用代理進行多平台開發時,必須明確記錄平台邊界。
共用程式碼組織
Shared/
├── MeditationSession.swift # Data model (all platforms)
├── SessionStore.swift # iCloud sync (all platforms)
└── SessionHistoryView.swift # UI (adapts per platform)
Return/ # iOS-specific
ReturnWatch Watch App/ # watchOS-specific
ReturnTV/ # tvOS-specific
代理規則:「若檔案位於Shared/,變更會影響所有平台。若檔案位於平台目錄中,變更則會被隔離。修改任何檔案前,務必先確認它所在的目錄。」
平台可用性防護
// HealthKit: available on iOS and watchOS, not tvOS
#if canImport(HealthKit)
import HealthKit
// HealthKit code here
#endif
// ActivityKit: available on iOS only
#if canImport(ActivityKit)
import ActivityKit
// Live Activity code here
#endif
// WatchKit: available on watchOS only
#if os(watchOS)
import WatchKit
// Watch-specific code here
#endif
代理指引:「使用平台專屬框架時,務必使用#if canImport()或#if os()防護。不要假設某個框架適用於所有 target。」
各平台UI調整
struct SessionHistoryView: View {
@Query var sessions: [MeditationSession]
var body: some View {
List(sessions) { session in
SessionRow(session: session)
}
#if os(tvOS)
.focusable()
#endif
#if os(iOS)
.swipeActions {
Button("Delete", role: .destructive) {
// delete
}
}
#endif
}
}
進階工作流程
自主建置、測試與修正迴圈
最強大的模式是:提供代理功能規格,讓它自主反覆執行建置、測試與修正迴圈。
Implement a countdown timer that:
1. Starts from a user-selected duration (10, 20, or 30 minutes)
2. Shows remaining time with a circular progress indicator
3. Plays a bell sound on completion
4. Logs the session to HealthKit as mindful minutes
Build after each change. Fix all errors. Run tests when the build succeeds.
Continue until all tests pass and the build is clean.
代理會撰寫程式碼、透過MCP建置、讀取結構化錯誤、加以修正後重複執行。原本需要人工進行5至10次建置、錯誤排除與修正的功能,可在單一自主迴圈中完成。
適用時機:具有明確驗收條件、定義完善的功能。
不適用時機:開放式功能(例如「讓它看起來更漂亮」)、對效能敏感的程式碼,或任何需要視覺驗證的內容。
iOS的子代理委派
Claude Code的子代理系統適用於iOS專案:
Use a subagent to research the best approach for implementing
iCloud key-value store sync for meditation sessions across iOS,
watchOS, and tvOS. Report back with the recommended pattern.
子代理會在獨立的內容視窗中探索文件與程式碼模式,回傳摘要後,再由主要工作階段實作建議。如此可避免研究工作耗用主要內容。
跨App模式套用
當您維護多個採用一致模式的iOS App時,代理可以將一個App的模式套用至另一個:
Look at how Settings.swift works in the Return project
(centralized singleton with validation). Apply the same pattern
to create a Settings.swift for the Water project.
代理會讀取來源模式、理解其結構,並在目標專案中建立一致的實作。
雙代理審查(Claude+Codex)
對於關鍵變更,請使用來自不同模型系列的兩個代理:
- Claude Code撰寫實作
- Codex CLI在獨立流程中進行審查
# After Claude implements the feature:
codex "Review the changes in the last commit. Focus on Swift 6.2
concurrency correctness, SwiftData relationship integrity,
and potential retain cycles. Report issues only — no praise."
不同模型系列能捕捉不同類型的錯誤。這對Metal shader與並行模式尤其有價值,因為這些領域很容易引入細微的錯誤。
雙重審查可捕捉、單一審查容易遺漏的問題:
| 問題類型 | Claude優勢 | Codex優勢 |
|---|---|---|
| SwiftData關聯循環 | 中等 | 強(GPT-5.6 Sol) |
| @MainActor隔離缺口 | 強 | 中等 |
| Metal buffer對齊 | 中等 | 中等 |
| Retain cycle偵測 | 強(Opus) | 強(GPT-5.6 Sol) |
| API淘汰警覺性 | 強(較新的訓練資料) | 中等 |
| 並行競爭條件 | 強 | 強(可捕捉不同模式) |
雙重審查的目的不是找出更多錯誤,而是找出不同的錯誤。每個模型系列在模式辨識上都有不同的失敗模式。
跨多個App的批次作業
當框架或模式變更影響多個App時:
# Update @Observable pattern across all projects
for project in BananaList Return Water Reps; do
cd ~/Projects/$project
claude -p "Audit all files for any remaining ObservableObject usage.
Convert to @Observable following the pattern in CLAUDE.md.
Build and test after changes." --dangerously-skip-permissions
done
請謹慎使用。非互動模式需要--dangerously-skip-permissions旗標,但它會略過所有安全檢查。請確認您的PreToolUse hooks已部署,以保護.pbxproj檔案。
使用Apple裝置端LLM的App
如果您的App呼叫Apple的Foundation Models framework(例如進行離線摘要、分類或結構化輸出生成),代理需要了解 prompt budget。iOS 26.4為SystemLanguageModel新增了兩個API,取代先前猜測的4096-token限制:contextSize(模型在單一對話中可接受的最大 token數)與tokenCount(for:)(async throws,回傳特定 prompt實際消耗的 token數)。31兩者皆為@backDeployed(before: iOS 26.4),因此無須使用#available階梯,即可在所有支援FM的OS版本中使用。
代理在產生prompt建構程式碼時,應遵循以下模式:
import FoundationModels
func budgetFor(prompt: String, reservedReply: Int = 256) async throws -> Int {
let model = SystemLanguageModel.default
let promptCost = try await model.tokenCount(for: prompt)
let budget = model.contextSize - promptCost - reservedReply
guard budget > 0 else { throw ContextError.promptTooLong }
return budget
}
若App會使用SystemLanguageModel,請將此模式加入您的CLAUDE.md。否則,代理會回退使用舊有的4096硬編碼,並在搭載更大內容視窗的裝置上悄悄截斷prompt。tokenCount(for:)的async throws簽名至關重要——若代理貼上同步版本,程式將無法編譯。
真實案例研究
抽象建議很容易。以下是來自這8個app的具體情境,說明代理輔助的iOS開發在實務上如何運作,也包含失敗案例。
案例研究1:為Return加入TV App(成功)
任務:為Return這款已有iOS與watchOS版本的冥想計時器加入tvOS target。TV app需要Siri Remote導覽、大螢幕UI,以及與iOS app同步設定。
代理做得好的部分:
- 讀取既有iOS TimerManager,並建立一個省略Live Activities與HealthKit(tvOS不支援)的TVTimerManager
- 為Siri Remote焦點導覽建立自訂按鈕樣式(TVCapsuleButtonStyle、TVCircleButtonStyle)
- 建立TVStepper元件,以+/-按鈕取代滾輪選擇器(無法搭配Siri Remote使用)
- 透過App Groups(group.com.941apps.Return)實作設定同步
- 在共用程式碼中加入#if os(tvOS)防護條件
- 使用platform=tvOS Simulator,name=Apple TV透過MCP建置並測試
我必須手動處理的部分: - 在Xcode中建立tvOS target(File > New > Target > tvOS App) - 將新的target加入Xcode專案(.pbxproj變更) - 為TV target設定App Groups entitlement - 將TV target加入既有scheme,或建立新的scheme - 手動將代理建立的所有Swift檔案加入TV target - 手動測試Siri Remote導覽(代理無法評估焦點行為)
結果:新增15個Swift檔案,TV app功能完整,約花3小時完成代理輔助開發。以我的估算,代理處理了約80%的實作工作;我則處理需要Xcode UI互動的部分(entitlements、target設定、capability flags),並在實體Apple TV上手動測試焦點。以這個程式碼庫來看,若比照我過去未使用代理推出類似功能的經驗,同等的單人作業會需要數天。
案例研究2:amp97中的Metal著色器偵錯(部分失敗)
任務:為示波器著色器加入以能量為基礎的強度系統。視覺化效果應隨音訊能量脈動。
發生了什麼:
1. 代理寫出有效的Metal著色器修改,加入uEnergy uniform與HDR tonemapping
2. 程式碼編譯無誤
3. 在裝置上,視覺化畫面完全變白,因為強度係數高了10倍(3.5而不是0.30)
4. 代理看不到白畫面,因此沒有回饋訊號
5. 我用肉眼辨識出問題,並要求代理降低係數
6. 代理降低了係數,但整體能量狀態機過於複雜,導致視覺化工具以不同方式壞掉
7. 完全還原,兩個commit(67959ed與cda4830)在869d914中被還原
教訓:Metal著色器是代理輔助開發中最困難的領域,因為回饋迴圈是斷裂的。代理可以驗證語法(可編譯)與語意(型別正確),但無法驗證輸出(看起來是否正確)。任何會改變視覺行為的著色器修改,都需要人在裝置上驗證。
這之後我加到CLAUDE.md的內容:「在未極度謹慎測試係數前,DO NOT嘗試修改示波器著色器的能量狀態。先前嘗試曾因係數高出10倍而破壞視覺化工具。」
案例研究3:Banana List中的SwiftData遷移(成功)
任務:將資料模型從V1遷移到V2,為GroceryItem加入quantity欄位,並新增帶有關聯的Category模型。
代理做了什麼:
1. 讀取既有V1模型定義
2. 建立帶有新欄位與關聯的V2模型定義
3. 撰寫符合SchemaMigrationPlan protocol的GroceryMigrationPlan
4. 實作V1toV2遷移階段:加入預設quantity: 1與category: nil
5. 更新所有view以支援新欄位
6. 更新SampleData.swift供preview使用
7. 透過MCP建置並執行測試,全數通過
8. 建立遷移專用單元測試
關鍵:代理成功,是因為SwiftData遷移遵循明確定義的protocol模式,而這個模式在Apple文件與訓練資料中都有充分呈現。CLAUDE.md明確記錄了V1模型,因此代理理解它要從什麼狀態遷移。
案例研究4:Return中的iCloud工作階段同步(成功,但具複雜度)
任務:實作跨裝置冥想工作階段記錄。在Apple TV或Mac上完成的工作階段,應同步到iPhone,以便寫入HealthKit記錄。
代理產出的內容:
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ tvOS │ │ Mac │ │ Watch │
│ TVTimerMgr │ │ TimerMgr │ │ WatchTimer │
└──────┬──────┘ └──────┬──────┘ └──────┬──────┘
│ │ │
└───────────────────┼───────────────────┘
│
▼
┌────────────────────────┐
│ SessionStore │
│ (iCloud Key-Value) │
└───────────┬────────────┘
│
▼
┌────────────────────────┐
│ iPhone (on foreground)│
│ → Write to HealthKit │
└────────────────────────┘
代理:
1. 建立MeditationSession資料模型,包含UUID、日期、時長、來源裝置,以及HealthKit同步狀態
2. 建立SessionStore singleton,用NSUbiquitousKeyValueStore管理iCloud同步
3. 實作合併衝突解決(以UUID去重)
4. 加入SessionHistoryView,並提供平台特定調整(iOS上的滑動刪除、tvOS上的焦點操作)
5. 接上iPhone端HealthKit同步,以處理來自其他裝置的工作階段
需要反覆調整的部分:初始實作沒有處理iPhone app在背景啟動的情境(沒有前景通知可觸發同步)。代理需要明確提示:「Use NSUbiquitousKeyValueStore.didChangeExternallyNotification to trigger sync on background KV changes.」在收到這個提示後,實作才正確。
教訓:當架構描述清楚時,代理能妥善處理多平台架構模式。iCloud同步模式並不簡單,但它遵循Apple已文件化的模式,代理能夠理解。邊界案例(背景同步)則需要人的領域知識,因為這部分並未被充分記錄。
案例研究5:Starfield Destroyer中的Game Center整合(成功)
任務:為太空射擊遊戲加入Game Center排行榜與成就。
代理做得好的部分:
- 在app進入點實作GKLocalPlayer.local.authenticateHandler
- 建立GameCenterManager,包含分數提交與成就回報方法
- 在所有Game Center操作前加入驗證狀態檢查
- 妥善處理離線情境(遊戲可在沒有Game Center時遊玩,重新連線後再提交)
- 建立符合8艘船進度系統的成就定義
需要手動處理的部分: - 在App Store Connect中建立排行榜與成就(網頁入口,代理無法存取) - 在Xcode中設定Game Center entitlement - 使用sandbox Game Center帳號測試(需要在裝置上手動登入)
使用代理的專案生命週期
開始新的 iOS 專案
使用代理協助開始新專案的最佳工作流程:
階段 1:人工設定(15-30 分鐘) 1. 建立 Xcode 專案(File > New > Project) 2. 設定簽署與功能 3. 設定部署目標與支援的目的地 4. 加入任何必要的 entitlements(HealthKit、Game Center 等) 5. 建立初始 CLAUDE.md,寫入專案身分與規則
階段 2:代理實作(數小時到數天) 1. 代理建立資料模型(SwiftData、Core Data 或單純的 structs) 2. 代理依照您記錄的模式建立 views 3. 代理在 manager/service classes 中實作商業邏輯 4. 代理撰寫單元測試 5. 透過 MCP 進行建置-測試-修正循環(自主)
階段 3:人工整合(30-60 分鐘) 1. 將代理建立的檔案加入 Xcode targets 2. 驗證簽署與 entitlements 3. 在實體裝置上測試 4. 檢視視覺版面與 UX 5. 提交至 App Store Connect
維護既有專案
針對已建立 app 的持續開發:
You: Here's the next feature for Return: add a "Focus Score" that
calculates from session duration and consistency. Show it on
the main timer view. Build and test.
Claude: [reads CLAUDE.md, understands patterns]
[reads TimerManager.swift, Settings.swift]
[creates FocusScore.swift — model with calculation logic]
[creates FocusScoreView.swift — display component]
[integrates into ContentView.swift]
[calls build_sim — 1 error: missing import]
[fixes import]
[calls build_sim — success]
[writes FocusScoreTests.swift]
[calls test_sim — all pass]
代理的成效會隨著 CLAUDE.md 反映專案現況的程度而提升。當您加入重要新功能、變更架構模式,或導入新 framework 時,請更新 CLAUDE.md。
何時該讓代理介入,何時不該
| 任務 | 代理? | 原因 |
|---|---|---|
| 新 SwiftUI view | 是 | 代理很擅長宣告式 UI |
| SwiftData model 變更 | 是 | 定義清楚、可測試 |
| 單元測試 | 是 | 機械式、以模式為基礎 |
| 重構 | 是 | 系統化、多檔案 |
| 建置錯誤診斷 | 是(透過 MCP) | 結構化回饋循環 |
| 新 Xcode target | 否 | 需要 Xcode UI、.pbxproj 變更 |
| 簽署與 provisioning | 否 | 以入口網站為基礎,代理無法存取 |
| 視覺潤飾 | 否 | 需要人工美感判斷 |
| Metal shader 調校 | 否 | 需要裝置 GPU 測試 |
| App Store 提交 | 否 | 入口網站與 Xcode Organizer |
| 效能 profiling | 否 | 需要 Instruments |
| Accessibility audit | 部分 | 代理可以加入 labels,由人工驗證 VoiceOver |
設定代理定義
如果您使用 Claude Code 的代理定義系統(.claude/agents/),請建立 iOS 專用代理:
---
name: ios-developer
description: iOS development agent with MCP build tools and SwiftUI expertise
tools:
- XcodeBuildMCP
- xcode
---
# iOS Developer Agent
You are an iOS development agent for apps targeting iOS 26+ with SwiftUI.
## Architecture Rules
- @Observable for all view models (NEVER ObservableObject)
- NavigationStack for all navigation (NEVER NavigationView)
- SwiftData for persistence
- Swift 6.2 strict concurrency
- @MainActor on all Observable classes
## Build & Test — Always Use MCP
Prefer MCP tools over raw shell commands for ALL build operations:
- **Build**: `build_sim` / `build_device` (NOT `xcodebuild` via Bash)
- **Test**: `test_sim` / `test_device` (NOT `xcodebuild test` via Bash)
- **Simulators**: `list_sims`, `boot_sim`, `open_sim`
- **Debug**: `debug_attach_sim`, `debug_stack`, `debug_variables`
- **Apple docs**: `DocumentationSearch` (NOT WebSearch for Apple APIs)
- **Swift verification**: `ExecuteSnippet` (NOT `swift` via Bash)
MCP returns structured JSON. Bash returns unstructured text.
## File Management Rules
- NEVER modify .pbxproj, .xcodeproj/, .xcworkspace/, .xib, .storyboard
- Create Swift files in the correct directory
- Report files that need manual addition to Xcode targets
## SwiftData Rules
- @Model classes are automatically Observable — do not add @Observable
- Use @Bindable for form bindings to model properties
- Use @Query in views, modelContext.fetch() elsewhere
- Document relationship delete rules
## When You Get Stuck
- Build errors: use `build_sim` via MCP for structured output
- API questions: use `DocumentationSearch` via Apple MCP
- Swift verification: use `ExecuteSnippet` via Apple MCP
- Never guess — verify with tools
在 Claude Code sessions 中使用 @ios-developer 參照此代理。
代理輔助 iOS 的測試模式
只要給予清楚指引,代理就能寫出優秀的單元測試。以下模式能產生最佳結果。
測試檔案組織
# In CLAUDE.md:
## Test Structure
Tests mirror source structure:
- `ReturnTests/TimerManagerTests.swift` tests `TimerManager.swift`
- `ReturnTests/SettingsTests.swift` tests `Settings.swift`
- `ReturnTests/ConstantsTests.swift` tests `Constants.swift`
Test naming: `test_<what>_<condition>_<expected>`
Example: `test_start_whenStopped_transitionsToRunning`
測試提示
有效的測試提示:
Write unit tests for TimerManager covering:
1. Initial state is .stopped with timeRemaining == selectedDuration
2. start() transitions state to .running
3. pause() from .running transitions to .paused
4. reset() from any state returns to .stopped with original duration
5. start() from .paused resumes (state becomes .running)
6. Edge case: reset() when already stopped is a no-op
7. Edge case: pause() when already paused is a no-op
Follow the existing test pattern in SettingsTests.swift.
Use setUp() to create a fresh TimerManager for each test.
這樣有效的原因: 編號的驗收標準會提供代理一份 checklist。參照既有測試檔案可建立模式。指定 setUp() 用法可避免代理建立糾結的測試狀態。
無效的測試提示:
Write tests for TimerManager.
這會產生泛泛而淺層的測試,漏掉邊界案例,也可能未遵循專案既有模式。
Async 測試模式
若要測試以 timer 為基礎與 async 程式碼:
// Agent produces this pattern when guided correctly:
final class TimerManagerTests: XCTestCase {
var sut: TimerManager!
@MainActor
override func setUp() {
super.setUp()
sut = TimerManager()
}
@MainActor
func test_start_whenStopped_transitionsToRunning() {
// Given
XCTAssertEqual(sut.state, .stopped)
// When
sut.start()
// Then
XCTAssertEqual(sut.state, .running)
}
@MainActor
func test_timerCountsDown_afterOneSecond() async throws {
// Given
sut.selectedDuration = 10
sut.reset()
sut.start()
// When
try await Task.sleep(for: .seconds(1.1))
// Then
XCTAssertLessThanOrEqual(sut.timeRemaining, 9.0)
}
}
代理需要提醒的關鍵模式:
- 測試 @MainActor classes 的測試方法需標註 @MainActor
- 使用 Task.sleep 或 async operations 的測試需使用 async throws
- 以時間為基礎的 assertions 需保留容忍範圍(1.1 秒,而不是剛好 1.0)
- 使用乾淨的 setUp() / tearDown() 確保測試隔離
Snapshot Testing
若要偵測視覺回歸,可以考慮加入 swift-snapshot-testing:
Add snapshot tests for the main timer view in three states:
1. Stopped (showing full duration)
2. Running (showing countdown)
3. Completed (showing 00:00 with completion state)
Use SnapshotTesting library. Create reference images on first run.
代理可以正確設定 snapshot tests,但無法審查參考圖片。您先審查初始 snapshots,之後代理的測試就能在未來變更中捕捉視覺回歸。
iOS 專案的上下文視窗管理
1M 上下文視窗(Opus 5)相當龐大,但並非無限。iOS 專案在上下文管理方面有其特定考量。
iOS 檔案的 Token 成本
| 檔案類型 | 一般大小 | 約略 Token 數 |
|---|---|---|
| SwiftUI 檢視(簡單) | 50-100 行 | 500-1,000 |
| SwiftUI 檢視(複雜) | 200-400 行 | 2,000-4,000 |
| SwiftData 模型 | 30-80 行 | 300-800 |
| 管理器/服務類別 | 100-300 行 | 1,000-3,000 |
| Metal 著色器(.metal) | 50-200 行 | 500-2,000 |
| 單元測試檔案 | 50-200 行 | 500-2,000 |
| CLAUDE.md | 100-300 行 | 1,000-3,000 |
| MCP 回應(建置) | 不一 | 200-2,000 |
| MCP 回應(測試) | 不一 | 500-5,000 |
若專案有 50 個檔案:讀取所有檔案約會消耗 50,000-100,000 個 Token,遠低於 1M 視窗的容量。代理程式可將整個專案保留在上下文中。
若專案有 100 個以上的檔案:便需要選擇性讀取。代理程式會先讀取 CLAUDE.md(取得檔案結構註解),再視需要讀取特定檔案。這正是 CLAUDE.md 中檔案註解至關重要的原因:它能引導代理程式直接找到正確檔案,無須逐一讀取全部內容。
大型專案的策略
- 詳細的 CLAUDE.md 檔案註解——代理程式讀取檔案對照表後,直接前往相關檔案
- 委派子代理程式——將探索與研究交由子代理程式處理(使用乾淨的上下文,並回傳摘要)
- 聚焦的提示詞——「修改 SettingsView.swift 以新增切換開關」優於「更新設定」
- 劃分工作階段——處理互不相關的功能時,應開啟新的工作階段,而非持續延長既有工作階段
- 使用
/compact——Claude Code 的壓縮指令會摘要對話並釋放上下文空間
MCP 的 Token 效率
支持使用 MCP 最有力的理由之一是:結構化的 JSON 回應所消耗的 Token,遠少於原始 xcodebuild 輸出。
| 情境 | 原始 Bash Token 數 | MCP Token 數 | 節省幅度 |
|---|---|---|---|
| 建置成功 | 3,000-10,000 | 200-500 | 85-95% |
| 建置失敗(1 個錯誤) | 3,000-10,000 | 300-800 | 90-92% |
| 測試結果(20 項測試) | 2,000-5,000 | 500-1,000 | 75-80% |
| 模擬器清單 | 500-2,000 | 200-400 | 60-80% |
在一般開發工作階段的 10-20 次建置循環中,相較於原始 xcodebuild,MCP 可節省 30,000-150,000 個 Token,讓這些 Token 得以用於實際的程式碼推理。
疑難排解
「build_sim 失敗——找不到 scheme」
代理程式猜錯了 scheme 名稱。修正方式:
Use discover_projs and list_schemes to find the correct scheme name
for this project before building.
或者,在 CLAUDE.md 中明確加入 scheme 名稱:
## Build
Primary scheme: `Return` (iOS)
Watch scheme: `ReturnWatch` (watchOS)
TV scheme: `ReturnTV` (tvOS)
「xcrun mcpbridge——找不到指令」
您需要 Xcode 26.3 或更新版本。請使用 xcodebuild -version 檢查。如果已安裝 Xcode 26.3 以上版本,但指令仍然失敗:
# Ensure Xcode command line tools are selected
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
# Verify
xcrun mcpbridge --help
「Claude Code 中未顯示 MCP 工具」
在工作階段進行期間註冊的 MCP 工具,可能要重新啟動後才會出現。退出 Claude Code,再啟動新的工作階段:
# Exit current session (Ctrl+C or /exit)
# Start fresh
claude
接著驗證:
You: List all available MCP tools from XcodeBuildMCP.
「代理程式一直透過 Bash 使用 xcodebuild,而非 MCP」
代理程式未透過 Tool Search 發現 MCP 工具。有兩種修正方式:
- 在 CLAUDE.md 中加入明確指引(請參閱教導代理程式使用 MCP)
- 直接提示:「使用 build_sim MCP 工具,不要透過 Bash 使用 xcodebuild」
「建置成功,但代理程式回報失敗」
XcodeBuildMCP 會剖析 xcodebuild 輸出。如果建置過程產生看似錯誤的警告(棄用警告尤其常見),代理程式可能會誤判結果。請查看 MCP 回應中的實際狀態欄位。
「模擬器在啟動期間停滯」
終止所有模擬器並重新啟動:
xcrun simctl shutdown all
xcrun simctl boot "iPhone 16 Pro"
或者要求代理程式:
Shut down all simulators, then boot a fresh iPhone 16 Pro.
「儘管 CLAUDE.md 有相關規則,代理程式仍嘗試修改 .pbxproj」
CLAUDE.md 規則只是建議,Hooks 才能強制執行。如果未設定 PreToolUse hook 來阻擋寫入 .pbxproj,代理程式終究會嘗試修改它。請安裝 hook:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"command": "bash -c 'INPUT=$(cat); FP=$(echo \"$INPUT\" | jq -r \".tool_input.file_path // empty\"); if echo \"$FP\" | grep -qE \"\\.(pbxproj|xcworkspace|xib|storyboard)$|xcodeproj/|xcworkspace/\"; then echo \"BLOCKED: Do not modify Xcode project files.\" >&2; exit 2; fi'"
}
]
}
}
規則說的是「請不要這麼做」。Hooks 說的則是「您不能這麼做」。
常見問題
我應該從哪個代理執行環境開始?
Claude Code CLI 搭配 XcodeBuildMCP。它具備最深入的 MCP 整合、最成熟的 hook 系統,以及可將整個 iOS 專案保留於工作記憶體中的 1M 上下文視窗(Opus 5)。建議先從這套組合開始;待工作流程日臻成熟,再加入 Codex 進行審查,並使用 Xcode 原生代理快速完成行內編輯。
我需要同時使用兩個 MCP 伺服器嗎?
對多數開發者而言,單獨使用 XcodeBuildMCP 就能涵蓋 90% 的需求(建置、測試、模擬器與偵錯)。若需要搜尋文件、驗證 Swift REPL,或算繪 SwiftUI 預覽,再加入 Apple 的 Xcode MCP 即可。日後隨時都能新增,因為兩個伺服器彼此獨立。
代理能從零開始建立新的 Xcode 專案嗎?
XcodeBuildMCP 包含鷹架工具(scaffold_ios_project、scaffold_macos_project),可根據範本建立新的 Xcode 專案。不過,對於正式環境的 App,我建議先在 Xcode 中建立專案(確保簽署、功能權限與 target 設定正確),再交由代理實作所有程式碼。花 5 分鐘操作 Xcode 的新專案精靈,可省下數小時處理由代理產生的專案設定問題。
代理如何處理 Swift Package Manager 相依套件?
處理得很好。Package.swift 是標準 Swift 檔案,代理能可靠地讀取及編輯。新增相依套件、更新版本範圍及設定 target 都可順利完成。限制在於以 .xcodeproj 為基礎的相依套件管理(Xcode 的套件解析 UI);這部分由 Xcode 管理,不應讓代理編輯。
代理能提交 App 至 App Store 嗎?
不能。提交至 App Store 涉及 Xcode 的 Organizer、佈建描述檔、螢幕截圖、中繼資料,以及 App Store Connect 入口網站。代理無法透過 MCP 或命令列工具,以具有實際意義的方式操作這些項目。代理能處理封存前的所有工作,包括實作、測試、修正錯誤及撰寫文件;最後的提交環節仍須由人工操作。
不過,代理可以協助準備 App Store 中繼資料。您可以要求代理根據最新變更撰寫 App 說明、關鍵字與版本更新內容。這類文字生成工作正是代理的強項。
在代理輔助的 iOS 開發中,該如何處理機密資訊與 API 金鑰?
切勿提交機密資訊。若 iOS App 需要連線至後端 API:
- 使用
.xcconfig檔案管理各環境的專屬設定 - 將
.xcconfig檔案加入.gitignore - 透過
Info.plist建置設定參照設定值 - 在 CLAUDE.md 中記錄所需的機密資訊,但不要包含實際值
## Configuration
API base URL and keys are in `Config.xcconfig` (not committed).
Required keys:
- `API_BASE_URL` — Backend server URL
- `API_KEY` — Authentication token
Create `Config.xcconfig` from `Config.xcconfig.template`.
代理知道這些金鑰存在及其使用位置,卻不會看到實際值。
SwiftUI 動畫呢?代理能撰寫嗎?
代理能正確撰寫動畫程式碼的語法,但無法以視覺方式驗證結果。簡單動畫(.animation(.spring())、.transition(.slide)、withAnimation { })通常能得到正確結果。至於講究精準時序的複雜多階段動畫,則需要反覆進行視覺調整,這是代理無法完成的。
有效:「計時器在不同狀態間切換時,加入彈簧動畫。」
無效:「讓計時器動畫感覺令人滿意。」(判斷主觀,需透過視覺方式調校。)
代理如何處理錯誤處理模式?
處理得非常好。代理熟悉 Swift 的 do/catch、Result 與 async throws 模式:
Implement error handling for the HealthKit authorization flow:
1. Check HKHealthStore.isHealthDataAvailable() — show alert if not
2. Request authorization — handle denial gracefully
3. On write failure — retry once, then show error
4. All errors should be user-facing with localized descriptions
代理能產生結構完善的錯誤處理程式碼,並提供適當的使用者訊息。不過,有時會過度處理錯誤(攔截原本應繼續向外傳遞的例外),因此請審查 catch 區塊。
可以使用代理實作輔助使用功能嗎?
可以,但只能完成一部分。代理能正確加入輔助使用標籤、提示與特性:
Add accessibility labels to all interactive elements in TimerView:
- Timer display: current time remaining
- Start/Pause button: current state and action
- Reset button: "Reset timer"
- Duration picker: selected duration
代理無法完成的工作包括:驗證 VoiceOver 導覽順序是否正確、測試 Dynamic Type 縮放,以及評估色彩對比度。請使用 Xcode 的 Accessibility Inspector 進行驗證。
如果不使用 SwiftData,代理如何處理 Core Data 遷移?
代理能撰寫 Core Data 遷移對應與模型版本,但無法自動完成 Xcode 中的手動步驟(建立新的模型版本、選取目前版本)。若仍使用 Core Data 而非 SwiftData,請在 CLAUDE.md 中記錄模型版本歷程:
## Core Data Model Versions
- V1: Initial (GroceryList, GroceryItem)
- V2: Added Category model (current)
- Migration: Lightweight automatic for V1→V2
代理如何處理 SwiftUI 預覽?
有兩種方式:
1. Apple Xcode MCP 的 RenderPreview 工具可在無頭環境中算繪預覽並回傳結果。代理能驗證預覽是否可順利編譯及算繪,但無法評估視覺結果是否正確。
2. 透過 build_sim 進行的建置式驗證,可確認預覽 provider 能否編譯。如果預覽在執行階段當機,建置仍會成功;只有在 Xcode 嘗試算繪預覽時,當機問題才會浮現。
若要以視覺方式驗證預覽,仍須開啟 Xcode。
visionOS 與 Apple Vision Pro 呢?
同樣的模式依然適用。XcodeBuildMCP 支援 visionOS 模擬器,而架構模式(@Observable、NavigationStack、SwiftData)也完全相同。RealityKit 專用程式碼(3D 內容、沉浸式空間、手部追蹤)具有與 Metal 相同的限制:代理能撰寫正確的程式碼,卻無法驗證空間呈現結果。
專案規模多大時,代理會開始難以應付?
限制因素是上下文視窗的大小。透過 Opus 5 的 1M token 視窗,Claude Code 可同時在工作記憶體中保留約 50 至 70 個 Swift 檔案。處理更大型的專案時,代理會利用檔案搜尋與選擇性讀取,針對程式碼庫的部分範圍作業。即使專案包含 100 個以上的檔案也能正常運作;代理只會按需讀取檔案,而不會將所有內容保留在上下文中。
實際限制不在於檔案數量,而是程式碼庫的一致性。具備詳細 CLAUDE.md 且文件完善的 200 檔案專案,成效會優於缺少文件的 30 檔案專案。
使用代理進行 iOS 開發前,需要懂 Swift 嗎?
您必須具備審查代理輸出及作出架構決策的能力。不必親自撰寫每一行程式碼,但對 Swift 的理解應足以察覺代理何時做出錯誤選擇,尤其是並行處理、記憶體管理與框架特有模式等方面。代理能將您既有的能力放大 10 倍,而非取而代之。
代理如何處理 Swift 檔案中的合併衝突?
代理能可靠地解決 Swift 原始碼檔案中的合併衝突。所有代理執行環境都能充分理解標準衝突標記(<<<<<<<、=======、>>>>>>>)。然而,.pbxproj 檔案中的合併衝突仍須手動解決;請勿要求代理處理 .pbxproj 衝突。
使用代理進行 iOS 開發的成本是多少?
使用 Anthropic 的 Max 方案(Opus 5、1M 上下文)時,一般 iOS 開發工作階段會持續 30 至 120 分鐘,並處理 200K 至 800K 個 token。MCP 工具呼叫只會增加少量額外負擔(相較於原始建置輸出,結構化 JSON 回應的 token 使用效率更高)。其成本與在其他程式碼庫中執行 Claude Code 相近;iOS 開發與網頁開發相比,費用並不會明顯更高或更低。
可以在 UIKit 專案中使用代理嗎?
可以,但代理處理 SwiftUI 的成效更好。UIKit 需要更多樣板程式碼、宣告式結構較少,而且經常涉及代理無法編輯的 Interface Builder 檔案。若您有 UIKit 專案,不妨讓代理負責模型層與商業邏輯,並手動處理 UI;也可以逐步將各個 view 遷移至 SwiftUI。
代理如何處理本地化?
代理能有效建立及編輯 .xcstrings(Xcode 字串目錄)檔案。它們可以新增本地化字串鍵、提供翻譯,並維持各語言間的一致性。.xcstrings 檔案採用結構化 JSON 格式,相當適合由代理處理。對於 .strings 檔案(舊版格式),代理的表現也很好;其鍵值格式簡潔明確。
iOS 中常見的 Agent 錯誤(以及如何預防)
以下是我在8個 iOS 專案、數千次 Agent 互動中反覆觀察到的錯誤。每一項都有相應的預防策略。
錯誤1:混用可觀察性模式
發生情況: Agent 在一個檔案中使用 @Observable,卻在另一個檔案中使用 ObservableObject;或是將 @Observable 加到本身已具備可觀察性的 @Model 類別。
預防方式: 在 CLAUDE.md 中明確訂定規則:
- NEVER use ObservableObject — use @Observable
- NEVER add @Observable to @Model classes (already Observable)
- NEVER use @StateObject — use @State with @Observable
- NEVER use @ObservedObject — access @Observable properties directly
錯誤2:在閉包中產生保留循環
發生情況: Agent 建立會強式擷取 self 的閉包,尤其常見於 Timer.publish、NotificationCenter 與完成處理常式。
預防方式: 在 CLAUDE.md 中加入閉包模式:
## Closure Pattern
- Timer callbacks: use `[weak self]` and guard
- NotificationCenter observers: store in `Set<AnyCancellable>` and use `[weak self]`
- Completion handlers: use `[weak self]` for any closure stored beyond the call site
錯誤3:忽略 @MainActor 要求
發生情況: Agent 建立 @Observable 類別時未使用 @MainActor 隔離,導致 Swift 6.2 並行警告;若 UI 更新未在主執行緒上進行,甚至可能造成執行階段當機。
預防方式:
## Concurrency Rule
ALL @Observable classes MUST be @MainActor:
```swift
@Observable
@MainActor
final class SomeManager { }
```
錯誤4:使用帶有目的地閉包的 NavigationLink
發生情況: Agent 使用已淘汰的 NavigationLink(destination:label:),而非型別安全的 NavigationLink(value:) 搭配 .navigationDestination(for:) 模式。
預防方式:
## Navigation Pattern
ALWAYS use value-based navigation:
```swift
NavigationLink(value: item) { ItemRow(item: item) }
.navigationDestination(for: Item.self) { ItemDetailView(item: $0) }
```
NEVER use: `NavigationLink(destination: ItemDetailView(item: item)) { }`
錯誤5:將模擬器名稱寫死
發生情況: Agent 撰寫建置命令時指定特定模擬器名稱(「iPhone 16 Pro」),但您的系統上可能沒有該模擬器。
預防方式: MCP 會處理這個問題——list_sims 能探索可用的模擬器。在 CLAUDE.md 中加入:
## Simulators
Do NOT hardcode simulator names. Use `list_sims` MCP tool to discover
available devices, then `boot_sim` with the discovered device ID.
錯誤6:在錯誤的目錄中建立檔案
發生情況: Agent 將新的檢視檔案建立在專案根目錄,而非 Views/ 子目錄;或是將模型放入錯誤的群組。
預防方式: CLAUDE.md 中的檔案結構註解可引導正確的放置位置。此外,請加入:
## File Placement Rules
- Views → `AppName/Views/`
- Models → `AppName/Models/`
- Managers → `AppName/Managers/`
- Extensions → `AppName/Extensions/`
- Tests → `AppNameTests/`
錯誤7:未處理平台可用性
發生情況: Agent 在會針對 tvOS 編譯的共用程式碼中使用 HealthKit(tvOS 不支援 HealthKit),或在 watchOS 程式碼中使用 ActivityKit。
預防方式:
## Platform Guards
- HealthKit: `#if canImport(HealthKit)` (unavailable on tvOS)
- ActivityKit: `#if canImport(ActivityKit)` (iOS only)
- WatchKit: `#if os(watchOS)`
- UIKit haptics: `#if os(iOS)` (unavailable on tvOS, watchOS uses WKHaptic)
錯誤8:將簡單功能過度工程化
發生情況: 原本只需20行工具函式即可完成,Agent 卻建立了通訊協定、通訊協定擴充、具體實作、工廠以及相依性注入容器。
預防方式: 加入化繁為簡的原則:
## Architecture Principle
Prefer the simplest solution that handles the requirements.
- Direct implementation over protocol abstraction (unless you have 2+ conforming types)
- Concrete types over generics (unless reuse is proven)
- Extensions on existing types over new wrapper types
坦誠評估
使用 AI Agent 發布8款 iOS App 後,以下是我的總結:
Agent 帶來轉變的部分: 實作速度。過去需要數天的工作,如今數小時即可完成。SwiftUI 檢視、SwiftData 模型、單元測試與重構,現在主要由 Agent 產出,再由人員審查。
Agent 未帶來轉變的部分: 架構決策、視覺設計、效能最佳化與 App Store 提交。這些工作仍由人員主導。
倍增效果確實存在,但有其上限。 以這8款 App 的整體經驗而言,我的主觀估計是:對於文件完備,且妥善設定 MCP 與 Hook 的專案,功能交付時間可改善3至5倍。這並非與控制組比較得出的結果,而是將同一程式碼庫中由 Agent 協助開發的功能,與單人完成同等工作的實際耗時進行比較。若專案缺少文件與 Hook,改善幅度可能只有1.5至2倍——Agent 會耗費太多時間猜測,而不是實際建置。33
值得投入之處: 花時間設定 CLAUDE.md、Hook 與 MCP。前期設定每投入1小時,日後便能省下許多修正 Agent 錯誤的時間。設定本身就是產品,而 Agent 則是執行引擎。
令我意外之處: MCP 伺服器徹底改變了合作模式。在 MCP 出現前,Agent 只是碰巧理解 Swift 的進階文字編輯器。導入 MCP 後,它們成為能撰寫、建置、測試、偵錯並反覆改進的開發夥伴。結構化回饋迴圈,正是「會寫程式碼」與「能交付程式碼」的 Agent 之間的關鍵差異。
我會告訴過去的自己: 從最小的 App 開始(Reps,14個檔案),先正確完成 MCP 與 Hook 設定,再撰寫詳盡的 CLAUDE.md,之後才將這些模式擴展到更大型的專案。不要從包含63個檔案的多平台 App 起步。無論專案規模大小,基礎架構的投入都相同——先在小型專案中完成一次,再複製到其他所有專案。
未來展望: Xcode 26.3 的原生 Agent 整合只是起點,並非終點。Apple 提供 MCP 支援,代表工具鏈正朝 Agent 優先的開發模式邁進。現在就投入打造 Agent 相容專案結構的開發者——包括清晰的 CLAUDE.md 檔案、可測試的架構與自動化 Hook——將隨著工具日益成熟,持續累積並放大這項投資的效益。
快速參考卡
安裝(一次性設定)
# XcodeBuildMCP (82 tools)
claude mcp add XcodeBuildMCP -s user \
-e XCODEBUILDMCP_SENTRY_DISABLED=true \
-- npx -y xcodebuildmcp@latest mcp
# Apple Xcode MCP (20 tools)
claude mcp add --transport stdio xcode -s user -- xcrun mcpbridge
# Codex MCP setup
codex mcp add xcode -- xcrun mcpbridge
# Verify
claude mcp list
CLAUDE.md 必備章節
1. Project identity (bundle ID, target OS, architecture)
2. File structure with annotations
3. Build and test commands
4. Key patterns and rules
5. Prohibitions (NEVER touch .pbxproj)
6. Framework-specific context
必備 Hook
{
"PreToolUse": [{ "matcher": "Edit|Write", "command": "block .pbxproj" }],
"PostToolUse": [{ "matcher": "Edit|Write", "command": "swiftformat" }]
}
架構規則
@Observable (not ObservableObject)
NavigationStack (not NavigationView)
@State (not @StateObject)
SwiftData @Model (not Core Data)
async/await (not completion handlers)
@MainActor (on all Observable classes)
.glassEffect() (Liquid Glass, iOS 26+)
MCP 工具優先順序
Build: build_sim (not xcodebuild via Bash)
Test: test_sim (not xcodebuild test via Bash)
Sim: list_sims/boot_sim (not xcrun simctl via Bash)
Docs: DocumentationSearch (not WebSearch)
REPL: ExecuteSnippet (not swift via Bash)
變更紀錄
| 日期 | 變更內容 | 來源 |
|---|---|---|
| 2026-08-16 | 修正Codex模型資訊,並納入Xcode 27的agent平台。 更正(面向讀者的錯誤):Codex CLI章節與雙重審查矩陣曾稱Codex「使用OpenAI模型(GPT-4o、o3)」。兩者都不是Codex模型。目前陣容為GPT-5.6 Sol/Terra/Luna,以及GPT-5.3 Codex Spark(僅文字的研究預覽版);GPT-5.4/GPT-5.4-mini將於2026-08-31從Codex退役。23 全文的Xcode 27 beta 5(27A5237l,8月10日)取代beta 4,其中兩項beta 5更新值得納入正文:agents可驗證watchOS app,包括Digital Crown、側邊按鈕與動作按鈕輸入(181147968);sudo xcrun mcp-server enable可預覽一個MCP伺服器,「無須開啟Xcode工作區即可執行」;其中的--unsafe-always-allow-all-agents適用於無人值守執行,但Apple與本指南都不建議在有人操作時使用(181836944)。7月29日更新遺漏的較大更正:「Xcode 26.3 Native Agents」章節描述的是Xcode 27自beta 1(6月8日)起便已取代的內嵌助理。agents如今可接受攜帶skills、MCP伺服器與ACP設定的plug-ins(178289210)、啟動simulators並合成觸控操作(175179787)、操控執行狀態及修改建置設定、entitlements與Info.plist鍵值(176935844),並在檔案系統存取安全層下執行(178289431)。章節已重新命名、限制清單已限定為26.x並補上27版更正、矩陣依版本重新編排,另加入操作警告:PreToolUse .pbxproj hook對Xcode內部沒有管轄權。另已記錄:LLDB自beta 2起內建自己的MCP伺服器lldb-mcp(176901842),因此「兩個伺服器」的說法現已改為三個。平台方面:iOS/iPadOS 26.6.1(23G82)與macOS 26.6.2(25G82)於8月10日發布。已確認未變:XcodeBuildMCP 2.7.0,以及Xcode 26/iOS 26的SDK上傳強制要求。 |
22 23 |
| 2026-07-29 | 平台追蹤結案:iOS、iPadOS與macOS 26.6已於7月27日正式發布。過去三列持續追蹤的未決事項已解決。iOS 26.6與iPadOS 26.6均以組建版本23G71發布,macOS 26.6則為25G72;同時推出的還有tvOS 26.6(23L773)、visionOS 26.6(23O770)與watchOS 26.6(23U67)。對曾以RC測試的人而言,有一點值得留意:23G71與Apple於7月20日釋出的iOS 26.6 RC組建版本相同,因此RC原封不動升格為正式版——已通過RC驗證的agent設定無須重新驗證。Xcode 27 beta 4(27A5228h,7月20日)仍是最新的Xcode beta,XcodeBuildMCP仍為2.7.0(7月23日發布),兩者自上次更新後均未變動。先前的變更紀錄列維持原文;它們記錄的是當時已知的資訊。 | 24 |
| 2026-07-28 | 渲染修正:重新連結10個孤立引用,恢復變更紀錄的來源欄。註腳2–11——本指南原始的引用集合——在後續更新迴圈將註腳12–22疊加其上時遺失了內文標記,導致10筆參考資料清單項目的返回箭頭指向頁面中不再存在的#fnref:N錨點。現在每一筆都已連結至其實際支持的主張:MCP規格連至協定定義;XcodeBuildMCP儲存庫與官方網站連至工具庫存與CLI指令數量;Apple的Xcode 26.3 MCP伺服器與Rudrank Riyam的獨立確認連至xcrun mcpbridge與XPC段落;Swiftjective-C連至原生Claude Agent與Codex供應商;Claude Code文件連至執行階段說明;SWE-bench連至結構化工具優於shell的論點;SwiftFormat連至儲存時格式化hook。此外,這份變更紀錄的標頭宣告兩欄,但每列實際上都有三欄,因此python-markdown依標頭寬度截斷每列並悄悄捨棄其來源儲存格;標頭現已改為三欄。渲染頁面的有效引用數:12→22。 |
- |
| 2026-07-25 | Claude Opus 5成為預設Opus模型;Claude Code MCP診斷功能。Claude Code v2.1.219(7月24日)將Claude Opus 5(claude-opus-5)設為預設Opus模型——1M context、每MTok基本費率$5/$25(與Opus 4.8相同)、fast mode費率$10/$50、知識截止於2026年5月,且effort預設為high;Opus 4.7已從fast mode移除,因此/fast現在代表Opus 5或Opus 4.8。指南中6處將1M context window歸於Opus 4.6的正文參考,現在均改為Opus 5(執行階段比較、比較表、context-management章節、執行階段建議,以及關於working-memory容量與session成本的兩個FAQ答案)。1M數字與約50個檔案的working-memory估計維持不變——這是模型名稱的時效性修正,而非能力修訂。同一版本也新增MCP連線診斷功能:當伺服器連線失敗時,claude mcp list與/mcp現在會回報HTTP狀態與錯誤文字;若MCP設定值帶有隱藏的前導或尾隨空白字元,系統會發出警告;headless stream-json init event新增了mcp_server_errors,列出因驗證失敗而跳過的--mcp-config項目。這些功能值得了解,但驗證章節維持原樣:HTTP狀態部分僅適用於遠端伺服器,而本指南安裝的兩個伺服器(npx xcodebuildmcp、xcrun mcpbridge)皆為stdio——空白字元警告與mcp_server_errors才是可能影響iOS設定的部分,通常是設定路徑中不慎貼入多餘空白。v2.1.219也新增sandbox.network.strictAllowlist,可在不提示的情況下拒絕sandboxed commands連線至未列入allowlist的主機;它與註腳20已追蹤的sandbox.allowAppleEvents項目並列。這是選用功能,且尚未在真實建置上測試;不過合理的iOS陷阱是sandboxed的SPM resolve或xcodebuild -resolvePackageDependencies連至github.com——啟用前請將套件主機加入allowlist。v2.1.220(7月25日)僅包含「Bug修正與可靠性改善」。平台追蹤:未變且仍未結案——iOS 26.6與macOS 26.6正式版尚未發布(RC於7月20日釋出;媒體預期目標約為7月27日)。 |
2025 |
| 2026-07-24 | XcodeBuildMCP 2.7.0。npm latest從2.6.2升至2.7.0(於2026-07-23發布)。重點是:UI automation tools現在可透過Device Hub完整支援Xcode 27 simulators——包括simulator視窗啟動與鍵盤控制——因此在iOS 27 beta上由agent驅動的UI驗證,不再需要退回使用Xcode 26 simulators;iOS 27章節與XcodeBuildMCP章節現已說明此事。破壞性變更:build/test tools會回傳schemaVersion: 3結構化結果(自2.6.0起為v2)——固定使用2版的validators需要更新。行為變更:省略configuration時,build/test/clean/app-path tools現在會遵循scheme action的configuration,而非一律使用Debug——Build & Test章節新增了操作指引(在假定Debug artifacts的情況下,請明確傳入configuration或使用session_set_defaults)。此外還有:可重複使用的.xctestproducts測試準備套件(無須重建即可重新執行測試、每次執行皆產生新的.xcresult)、session-default extraArgs、新的xcodebuildmcp purge工作區儲存空間指令,以及修正MCPclients等待10–17秒才可使用工具的問題(錯誤失敗的health checks)。例行維護:正式儲存庫首頁為github.com/getsentry/XcodeBuildMCP——npm的repository欄位指向該處,舊的cameroncooke URL會301重新導向——因此已更新剩餘的舊URL引用;工具庫存已確認在2.7.0維持不變(文件仍宣稱12個工作流程共有82項工具;對2.6.2與2.7.0進行等效stdio tools/list後,回傳的庫存完全相同,CLI仍為100個指令/72個canonical)。平台追蹤:延續上一列,仍未結案——iOS 26.6 RC(23G71)於7月20日推出,iOS/macOS 26.6正式版預期即將發布(約7月27日)。 |
1921 |
| 2026-07-21 | Xcode 26.6正式版與Xcode 27更正、XcodeBuildMCP 2.6.x、Claude Code自動背景執行。Xcode 26.6於2026-06-25正式發布(組建版本17F113;RC為6月8日、RC 2為6月18日),並帶來3項與agent相關的Coding Intelligence變更:Google Gemini成為coding-assistant provider(171990272)、支援Agent Client Protocol(178294840),使任何相容ACP的agent皆可插入Intelligence面板,以及Preview Snapshot MCP variant rendering——淺色/深色、方向、字體大小(178831772);它內含Swift 6.3與iOS 26.5世代的SDK,需要macOS Tahoe 26.2以上,並修正兩個agent turn crash及agent提問時發生的hang。先決條件現在建議使用26.6以上。更正:下方2026-06-08列表示Apple尚未發布已驗證的「Xcode 27」版本——這在撰寫當時即有誤:Xcode 27 beta(27A5194q)在WWDC第一天便登上Apple releases頁面,目前已至beta 4(27A5228h,2026-07-20),搭配Swift 6.4與macOS Tahoe 26.4以上環境中的iOS 27 SDK;iOS 27章節現在涵蓋其內容(Coding Intelligence plan mode已知問題178673449、RenderPreview groups與localization previews、「Prepare Project for Localization」已移除鍵值的回報、27.0上的ASan需要Xcode 26.5以上)。XcodeBuildMCP從2.5.2升至2.6.2(npm latest,6月2日):v2.6.0「runtime UI automation」版本為snapshot_ui新增穩定element refs與screen hashes(sinceScreenHash略過),新增wait_for_ui/batch/dragtools、type_text的replaceExisting、v2-schema結果中的nextSteps,以及選用的XCODEBUILDMCP_HEADLESS_LAUNCH;工具數量已從「8個分類共59項」更正為12個工作流程分類中的82項MCP工具(CLI:100個指令、72個canonical),包括可經由XcodeBuildMCP呼叫僅限Xcode-IDE的MCPtools的新xcode-ideproxy。Claude Code v2.1.212(7月16日)會自動將執行超過2分鐘的MCPcalls轉至背景(CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS可調整或停用)——xcodebuild builds與tests經常超過這個時間——而v2.1.206(7月9日)修正了每個伺服器的request_timeout_ms遭忽略的問題(新session中長時間calls會套用預設60秒逾時);v2.1.181(6月17日)新增sandbox.allowAppleEvents,並修正sandboxed sessions中open/osascript發生的macOS error -600,讓open -a Simulator工作流程恢復可用。平台追蹤:iOS 26.6 RC(23G71)與iOS 27 beta 4均於7月20日推出——iOS 26.6正式版即將發布;App Store年齡分級問卷於7月9日新增社群媒體問題,自2026年9月起,新提交項目與更新均須作答。 |
17181920 |
| 2026-06-08 | WWDC 2026/iOS 27 beta。新增「iOS 27與WWDC 2026:您的Agent現在使用什麼進行建置」章節與TL;DR說明。iOS 27自6月8日keynote起進入beta;iOS 26仍為正式發布版本,因此本章將新frameworks定位為以iOS 27 beta SDK為目標的內容,而agent-development workflow(runtimes、MCP、CLAUDE.md、hooks)維持不變。與agent相關的新增功能,每一項均交叉連結至已驗證的深度解析:Foundation Models GenerationOptions.ToolCallingMode與內建Vision tools(OCRTool/BarcodeReaderTool);App Intents LongRunningIntent/performBackgroundTask、SyncableEntity、IndexedEntityQuery;新的Core AIframework(在Apple Silicon上執行自己的模型);新的Evaluationsframework(用於模型品質的XCTest);以及SwiftData observation/history、HealthKit workout zones與SwiftUI iOS 27。Xcode版本建議維持不變——Apple尚未發布已驗證的「Xcode 27」版本,因此指南維持推薦Xcode 26.5-stable;操作注意事項是要在agent context中指明這些frameworks,因為2026年6月之前的模型預設採用iOS 26的形式。 |
1213141516 |
| 2026-05-28 | Beta channel與WWDC26脈絡。Apple Developer(5月26日)宣布iOS 26.6、iPadOS 26.6、macOS 26.6、tvOS 26.6、visionOS 26.6與watchOS 26.6的beta releases,並同步推出Xcode 26.6 beta;行動呼籲明確表示應以Xcode 26.5搭配新的beta SDK進行建置與測試,因此agent workflows應將xcode-select固定於stable Xcode 26.5(組建版本17F42),同時並行安裝beta SDK以進行向前相容性測試,而非將DEVELOPER_DIR切換至beta。WWDC26(5月18日公告)預定於2026年6月8日至12日舉行——這很可能是Swift、SwiftUI、App Intents、Foundation Models與on-device agent API的下一個轉折點。本指南中的Coding Intelligence與Foundation Models指引仍以Xcode 26.5 stable為目標;beta-channel SDK尚不建議作為生產環境agent workflows的基礎。Apple Developer(5月21日)也宣布自2026年6月18日起,澳洲與越南適用年齡分級變更——雖非agent指引,但值得為portfolio compliance加以標示。 |
27 |
| 2026-05-24 | 將Xcode 26.5正式版發布日期更正為2026-05-11,並根據Apple releases頁面將組建版本固定為17F42。本次本機驗證:xcodebuild -version回傳Xcode 26.5/Build version 17F42;xcodebuildmcp的npm latest回傳2.5.2,time.modified為2026-05-12T07:40:41.737Z。27 |
|
| 2026-05-16 | 將建議的Xcode升級至26.5+(於2026-05-11發布)。兩項新的Coding Intelligence功能與agent workflows相關:現在可將訊息排入coding assistant佇列,因此無須等待回應即可安排下一個請求;agents也能在繼續前提出澄清問題——兩者都可減少將Xcode原生agents與Claude Code或Codex sessions並行執行的摩擦。27 XcodeBuildMCP最新狀態檢查:v2.5.2(2026-05-12)是最新版,加入內建AXe 1.7.0及log-capture filter-validation問題修正;v2.1.0+的xcodebuildmcp init流程仍是建議的安裝方式。 |
|
| 2026-04-28 | 將agent workflows建議的Xcode升級至26.4+(26.4.1、2026-04-16、組建版本17E202為最新正式版,僅含Bug修正)。引用對agent撰寫tests與localization有用的Xcode 26.4功能(2026-03-24、組建版本17E192):Swift Testing image attachments、Issue.record的severity、附帶crashlogs的UI-test crash warnings(特別針對XCUIApplication(bundleIdentifier:)/XCUIApplication(url:)apps)、String Catalog editor improvements。新增xcodebuildmcp initauto-installer(v2.1.0+、2026-02-23),作為手動MCP設定的替代方案。 |
|
| 2026-04-27 | App Store Connect:自2026-04-28起強制使用Xcode 26+提交。Foundation Models新增SystemLanguageModel.contextSize與tokenCount(for:) API(back-deployed至iOS 26.4)——新增agent-generated FM prompt-budget code模式。iOS 26.4.2(4月22日)與iOS 26.5 beta 3(4月20日)發布,但沒有影響agent toolchain的變更。 |
|
| 2026-04-13 | 初次發布。8個apps、3個runtimes、MCP設定、CLAUDE.md模式、hooks、案例研究。 |
參考資料
-
XcodeBuildMCP 預設包含 Sentry 遙測功能。專案的隱私權文件詳述會傳送的內容:錯誤訊息、堆疊追蹤,以及某些情況下的檔案路徑。設定環境變數
XCODEBUILDMCP_SENTRY_DISABLED=true可完全停用。 ↩ -
Anthropic,「Model Context Protocol Specification」,modelcontextprotocol.io/specification。MCP 規格定義 JSON-RPC 傳輸、工具探索及資源通訊協定,XcodeBuildMCP 與 Apple 的 Xcode MCP 均有實作。 ↩
-
XcodeBuildMCP,github.com/getsentry/XcodeBuildMCP。由 Sentry 維護的開放原始碼專案。涵蓋模擬器、裝置、偵錯、UI 自動化、覆蓋率及 Swift 套件,共有 12 個工作流程類別中的 82 項工具(截至 v2.6.x)。採用語意化版本控制並提供變更日誌。 ↩
-
Apple 將 Xcode MCP 伺服器納入 Xcode 26.3 智慧開發工具計畫,將 MCP 定位為 AI 程式設計助理與 Xcode 工具鏈之間的介面層。請參閱官方的 Xcode Release Notes 文件。 ↩
-
Rudrank Riyam,「Exploring Xcode Using MCP Tools」,rudrank.com/exploring-xcode-using-mcp-tools-cursor-external-clients,2026。獨立確認 Apple 的 MCP 工具數量、XPC 相依性及文件搜尋能力。 ↩
-
Jimenez, C.E., Yang, J., Wettig, A., et al.,「SWE-bench: Can Language Models Resolve Real-World GitHub Issues?」ICLR 2024。arxiv.org/abs/2310.06770。具備結構化工具存取權的代理,在表現上明顯優於僅限使用非結構化 shell 指令的代理。此發現驗證了結構化 MCP 介面對代理效能的價值。 ↩
-
Claude Code CLI 文件,code.claude.com。涵蓋 Hook 系統、MCP 設定、子代理委派及代理定義。 ↩
-
SwiftFormat,github.com/nicklockwood/SwiftFormat。用於 PostToolUse hooks 的 Swift 格式化工具,確保程式碼風格一致。 ↩
-
XcodeBuildMCP 官方網站,xcodebuildmcp.com。工具參考資料宣稱有 82 項按工作流程分組的 MCP 工具;CLI 列出橫跨 12 個類別的 100 項指令(72 項標準指令)。可透過 Homebrew 或 npx 安裝。 ↩
-
Swiftjective-C,「Agentic Coding in Xcode 26.3 with Claude Code and Codex」,swiftjectivec.com,2026年2月。確認 Xcode 26.3 透過 Settings > Intelligence 提供原生 Claude Agent 與 Codex 執行階段支援。透過
xcrun mcpbridge暴露 20 項 MCP 工具。 ↩ -
Blake Crosley,「Two MCP Servers Made Claude Code an iOS Build System」,blakecrosley.com/blog/xcode-mcp-claude-code,2026年2月。介紹設定流程,以及同一作者 iOS 開發工作流程中的實務成果。 ↩
-
Foundation Models in iOS 27: Tool-Calling Control,來源為 Apple iOS 27 beta 的 Foundation Models 文件(
GenerationOptions.ToolCallingMode、OCRTool、BarcodeReaderTool)。WWDC 2026;於2026年6月8日驗證。 ↩↩ -
App Intents in iOS 27: Background, Sync, Spotlight,來源為 Apple iOS 27 beta 的 App Intents 文件(
LongRunningIntent、performBackgroundTask(options:operation:)、SyncableEntity、IndexedEntityQuery)。WWDC 2026;於2026年6月8日驗證。 ↩↩ -
Core AI: Running Models on Apple Silicon,介紹新的 iOS 27/macOS 27 Core AI 框架,可在 Apple Silicon 上執行您自己的模型。WWDC 2026;於2026年6月8日驗證。 ↩↩
-
Evaluations: XCTest for Model Quality,介紹新的 macOS 27 Evaluations 框架,可在測試套件中衡量模型輸出品質。WWDC 2026;於2026年6月8日驗證。 ↩↩
-
SwiftData in iOS 27: Observation and History、HealthKit in iOS 27: Workout Zones, New Types與What’s New in SwiftUI for iOS 27,均取材自 Apple 的 iOS 27 beta 文件。WWDC 2026;於2026年6月8日驗證。 ↩↩
-
Apple,「Xcode 26.6 Release Notes」與 Apple Developer Releases。Xcode 26.6(build 17F113)列於2026年6月25日;RC(17F109)為2026年6月8日,RC 2(17F113)為2026年6月18日。引自發行說明:「Google Gemini 現已可用於程式設計助理」(171990272);「Xcode 新增對 Agent Client 通訊協定的支援」(178294840);「Preview Snapshot MCP 工具現在可轉譯淺色/深色外觀、直向/橫向方向及各種字級覆寫等變體」(178831772);修正了在作用中代理回合期間關閉視窗時發生的當機(174186260)、代理檔案操作涉及非絕對路徑時發生的當機(174752919),以及「當代理向使用者提問時可能導致 Xcode 無限期卡住的錯誤」(177989242)。Xcode 26.6 包含 Swift 6.3 與適用於 iOS 26.5、iPadOS 26.5、tvOS 26.5、watchOS 26.5、macOS 26.5 及 visionOS 26.5 的 SDKs;需要 macOS Tahoe 26.2 或以上版本。發行說明文字於2026年7月21日驗證。 ↩↩↩↩↩↩↩
-
Apple,「Xcode 27 Release Notes」與 Apple Developer Releases。Xcode 27 beta(27A5194q)列於2026年6月8日——WWDC 第一天;beta 4(27A5228h)列於2026年7月20日。Xcode 27 beta 4 包含 Swift 6.4 與適用於 iOS 27、iPadOS 27、tvOS 27、watchOS 27、macOS 27 及 visionOS 27 的 SDKs;需要 macOS Tahoe 26.4 或以上版本。引用項目包括:計畫模式確認列(「Implement the plan?」)的已知問題——代理仍在串流時點擊,可能觸發重疊的代理回合(178673449);RenderPreview MCP 工具支援使用新的群組功能轉譯 Previews(174692209),並以不同在地化設定預覽 UI(181040291);「Prepare Project for Localization」代理工具現在會顯示已從來源移除、不再出現的 String Catalog keys(179755385);使用 Xcode 26.4 或更早版本建置時,Address Sanitizer 可能無法在 iOS/tvOS/watchOS/visionOS 27.0 上啟動——因應方式是使用 Xcode 26.5+(178072780)。發行說明文字於2026年7月21日驗證。 ↩↩↩↩↩↩
-
XcodeBuildMCP v2.6.0 release,2026年6月1日(「執行階段 UI 自動化」);隨後發布 v2.6.1 與 v2.6.2,且 v2.6.2 為 npm 最新版(於2026年7月21日驗證:
npm view xcodebuildmcp dist-tags.latest→2.6.2,發布於2026年6月2日)。工具數量取自官方文件(xcodebuildmcp.com/docs/tools:「XcodeBuildMCP 宣稱提供的全部 82 項工具,依工作流程分組」),並於2026年7月21日在本機依 v2.6.2 交叉驗證:xcodebuildmcp tools回報 12 個工作流程類別中的 100 項 CLI 指令(72 項標準指令)(coverage、debugging、device、macos、project-discovery、project-scaffolding、simulator、simulator-management、swift-package、ui-automation、utilities、xcode-ide),且在啟用全部 12 個工作流程的情況下,stdiotools/list回傳本指南清單表所使用的工具名稱,包括wait_for_ui、batch、drag、xcode_ide_list_tools與xcode_ide_call_tool。約 70% 的實際耗時/約 68% 的 token/約 76% 的工具呼叫減少數據,是專案針對確定性 Weather-app 工作所做的自身基準測試,並非獨立測量。 ↩↩↩↩↩↩ -
Claude Code CHANGELOG。v2.1.212(2026年7月16日):「執行超過 2 分鐘的 MCP 工具呼叫現在會自動移至背景,讓工作階段維持可用;可設定門檻,或使用
CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS停用。」v2.1.206(2026年7月9日):「修正透過--mcp-config或.mcp.json設定的 MCP 伺服器忽略各伺服器request_timeout_ms的問題;此問題會導致長時間執行的 MCP 工具呼叫在新工作階段中於預設 60 秒逾時。」v2.1.181(2026年6月17日):「新增sandbox.allowAppleEvents選擇加入設定,讓沙箱化指令可在 macOS 上傳送 Apple Events」以及「透過新增 Apple Events 權限,修正 macOS 上open、osascript與瀏覽器式驗證流程因錯誤 -600 失敗的問題。」v2.1.219(2026年7月24日):「伺服器無法連線時,將 HTTP 狀態與錯誤文字新增至claude mcp list與/mcp」;「針對含有隱藏前導或尾端空白的 MCP 設定值新增警告」;「將mcp_server_errors新增至無頭 stream-json init 事件,列出遭略過的--mcp-config項目」;以及「新增sandbox.network.strictAllowlist設定,用於拒絕沙箱化指令連線至未列入允許清單的主機。」v2.1.220(2026年7月25日)僅列出「錯誤修正與可靠性改進」。變更日誌文字於2026年7月21日驗證;v2.1.218-v2.1.220 項目於2026年7月25日驗證。 ↩↩↩↩↩ -
XcodeBuildMCP v2.7.0 release,2026年7月23日;npm 最新版於2026年7月24日驗證(
npm view xcodebuildmcp dist-tags.latest→2.7.0,發布於2026-07-23T14:07Z)。引自發行說明:Xcode 27 Device Hub——「UI 自動化工具現在可透過 Device Hub 完整支援 Xcode 27 模擬器,包括啟動模擬器視窗與鍵盤控制」;破壞性變更——建置與測試工具回傳schemaVersion: 3,會影響固定使用版本 2 的驗證器;行為變更——「未指定 configuration 時,建置、測試、清理及 app-path 指令現在會遵循 scheme action 的 configuration,而非一律使用 Debug」;另外還有.xctestproducts可重複使用的測試準備套件、xcodebuildmcp purge工作區儲存空間指令(預設為 dry-run)、工作階段預設extraArgs與每次呼叫覆寫,以及「修正 MCP 用戶端等待工具可用長達 10–17 秒的問題,該問題可能讓簡短的健康檢查回報連線失敗。」儲存庫首頁:npm 的repository欄位指向github.com/getsentry/XcodeBuildMCP,且github.com/cameroncooke/XcodeBuildMCP會 301 重新導向至該處(兩者均於2026年7月24日檢查)——請引用 getsentry URL。工具數量:發行說明未列出數量,官方文件(xcodebuildmcp.com/docs/tools)仍宣稱「全部 82 項工具」(於2026年7月24日擷取);在本工作階段中,以相同條件的 stdiotools/list對xcodebuildmcp@2.6.2 mcp與@2.7.0 mcp交叉驗證(啟用相同 12 個工作流程,並確認各版本的serverInfo.version):兩者回傳完全相同的工具清單(此環境暴露 76 項——宣稱的 82 項包含依環境條件而定的工具),且 2.7.0 的xcodebuildmcp tools仍回報相同 12 個類別中的 100 項指令、72 項標準指令。因此,82 項、12 類別的清單可不變地延續至 v2.7.0。 ↩↩↩↩↩↩↩ -
Apple,「Xcode 27 Release Notes」,於2026年8月16日從 DocC JSON 讀取(HTML 頁面以用戶端方式轉譯,且不會向擷取工具回傳文字)。Beta 5(27A5237l,2026年8月10日)原文:「Coding Intelligence agents can now verify watchOS apps, including rotating and pressing the Digital Crown, and pressing the side and Action buttons (Apple Watch Ultra). (181147968)」以及「Xcode 27 Beta 5 adds a preview of a new MCP server experience that runs without requiring an open Xcode workspace… You can turn this experience on by using
sudo xcrun mcp-server enable. Check its state afterward withxcrun mcp-server status… Developers running agents in unattended environments can approve all permissions upfront withsudo xcrun mcp-server enable --unsafe-always-allow-all-agents. This is not a recommended configuration for at-desk use. (181836944)」。Beta 1(2026年6月8日):具備 skills、MCP 伺服器及 ACP 設定的 plug-ins(178289210);檔案系統存取安全層(178289431);模擬器啟動、安裝、開啟、觸控合成與螢幕截圖擷取(175179787);MCP 偵錯器、scheme 及 build-settings/entitlements/Info.plist 工具(176935844);一級支援的規劃功能(172857081);專案洞察(177568662)。Beta 2:「LLDB 現在隨附 MCP 伺服器(lldb-mcp)」(176901842)。建置編號與日期均已對照 Apple Developer Releases。 ↩↩↩↩↩↩↩↩ -
OpenAI,Codex models(developers.openai.com/codex/models 重新導向的正式目標),於2026年8月16日擷取。建議使用:「5.6 Sol——適用於複雜程式設計、電腦操作、研究及網路安全的最強 GPT-5.6 旗艦模型」;「5.6 Terra——適合日常工作的平衡型 GPT-5.6 模型」;「5.6 Luna——快速且經濟實惠的 GPT-5.6 模型」。GPT-5.3 Codex Spark 是僅限文字的研究預覽版。該頁面指出,GPT-5.4 與 GPT-5.4-mini 將於2026年8月31日自 Codex 退役,改由 5.6-terra 與 5.6-luna 取代。GPT-4o 與 o3 均未列為 Codex 模型。 ↩↩↩
-
Apple Developer releases feed。iOS 26.6(23G71)、iPadOS 26.6(23G71)、macOS 26.6(25G72)、tvOS 26.6(23L773)、visionOS 26.6(23O770)及 watchOS 26.6(23U67)均標示為2026年7月27日星期一。7月20日的 iOS 26.6 RC 使用相同的 23G71 建置編號,因此該 RC 即為正式版。Xcode 27 beta 4(27A5228h)標示為2026年7月20日星期一,仍是最新的 Xcode 項目。已於2026年7月29日依 releases RSS feed 驗證。 ↩
-
Anthropic,「Introducing Claude Opus 5」(2026年7月24日)與models overview。Claude Opus 5(
claude-opus-5):100 萬 token context window(預設值亦為最大值)、128K 最大輸出、每 MTok $5/$25——與 Opus 4.8 的基本定價相同——快速模式則為 $10/$50,可靠知識截止日期為2026年5月。effort在 Claude API 與 Claude Code 中預設為high。Claude Code CHANGELOG v2.1.219(2026年7月24日):「新增 Claude Opus 5(claude-opus-5),現在是預設 Opus 模型——100 萬 context、快速模式為每 Mtok $10/$50。」Opus 4.7 已從快速模式移除;/fast現在適用於 Opus 5 與 Opus 4.8。於2026年7月25日驗證。 ↩↩ -
Apple Developer News,「Upcoming Requirements」。2026年4月28日的項目:「上傳至 App Store Connect 的 App 必須使用 Xcode 26 或以上版本建置,並搭配適用於 iOS 26、iPadOS 26、tvOS 26、visionOS 26 或 watchOS 26 的 SDK。」此要求所列的平台不包括 macOS。 ↩
-
Apple,「Xcode 26.5 Release Notes」與「Xcode 26.5 (17F42) - Releases」。Apple 於2026年5月11日列出 Xcode 26.5,建置編號為 17F42。發行說明引用的兩項 Coding Intelligence 功能:無須等待目前回應完成,即可在程式設計助理中將訊息排入佇列(174563016);代理可在繼續前提出釐清問題以蒐集脈絡(175182375)。亦包含對 12 個月承諾制月訂閱的 StoreKit Testing 支援(
PricingTermsmodel、billingPlanTypePurchaseOption、Transaction與SubscriptionRenewalInfo上的CommitmentInfo),以及修正 Swift Tasks 在 async/await 操作期間遷移執行緒時進行逐步偵錯的 Swift 偵錯器問題。目前工作階段於2026年5月24日驗證:xcodebuild -version回傳Xcode 26.5與Build version 17F42;npm view xcodebuildmcp version dist-tags.latest time.modified --json回傳最新版2.5.2,其time.modified為2026-05-12T07:40:41.737Z。另請參閱:9to5Mac,「Xcode 26.5 adds two features that make agentic coding more useful」,2026年5月12日。 ↩↩↩↩ -
Apple,「Xcode 26.4 Release Notes」。Xcode 26.4(2026年3月24日,build 17E192)。發行說明所引用的功能:Swift Testing 現在支援透過
CGImage、NSImage、UIImage及CIImage附加影像;Issue.record接受嚴重性等級;部分 UI-test App 當機——具體而言,透過XCUIApplication(bundleIdentifier:)或XCUIApplication(url:)操作的 App——會以附加 crashlogs 的警告呈現,而不會使測試失敗;String Catalog 編輯器新增項目剪下/複製/貼上、移除語言,以及依既有語言預先填入翻譯的功能,另有BUILD_ONLY_KNOWN_LOCALIZATIONS設定。 ↩ -
Apple Developer News,「Xcode 26.4.1 (Build 17E202) Now Available」,2026年4月16日。僅為錯誤修正的點版本——修正 iOS/macOS/visionOS 早於 26.4 版本中因缺少符號導致的 MetricKit 當機,以及 Swift async 堆疊配置錯誤(
swift_asyncLet_finish中的「freed pointer was not the last allocation」)。 ↩ -
getsentry/XcodeBuildMCP v2.1.0 release,2026年2月23日。新增
xcodebuildmcp initCLI 指令,可一次安裝代理 skills 與 MCP 設定,取代獨立的install-skill.sh指令碼。自動偵測 Claude Code、Cursor 與 Codex;支援--print(為不受支援的用戶端將設定寫入 stdout)及--uninstall(移除)。 ↩ -
InfoQ,「Apple Adds Context Window Management to Foundation Models」,2026年3月。記錄新的
SystemLanguageModel.contextSize與tokenCount(for:)APIs,並確認@backDeployed(before: iOS 26.4)註解。取代先前社群對 4096-token 硬編碼的猜測。 ↩ -
檔案計數來自2026年4月27日,針對八個私有 App 儲存庫各自執行
find . -name '*.swift' -not -path '*/Tests/*' | wc -l。未納入測試檔案。總數與 §The Portfolio 中各 App 的細分表一致。 ↩ -
主觀的實際耗時估計,並非相對於對照組的測量。3-5x 數據是作者回憶2026年採用代理輔助的功能開發時間,與在代理工作流程之前於相同程式碼庫中發布之等效單人功能的比較。請將其視為完成 MCP + hook 設定後的預期啟發,而非基準測試。 ↩