💡 前置阅读推荐:如果你还不了解Claude Code子代理的基础概念,强烈建议先阅读我的上一篇文章《Claude Code子代理完全指南:从0到1构建你的AI编程军团》,它会帮你理解子代理的核心机制和配置方法。
今天要分享的是我精心打磨的iOS开发子代理——这个配置能让Claude Code像一个精通苹果生态的资深iOS架构师,从SwiftUI到性能优化,从App Store审核到苹果全家桶集成,一个子代理搞定所有。
iOS开发不仅仅是写Swift代码,更是要融入整个苹果生态系统:
// 场景对比:创建一个列表界面
// ❌ 通用Claude可能给你的代码
class ViewController: UIViewController {
@IBOutletweakvar tableView: UITableView!
var items = ["Item 1", "Item 2"] // 没有数据模型
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count// 没有错误处理
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell() // 没有复用!内存问题!
cell.textLabel?.text = items[indexPath.row]
return cell
}
}
// 问题:老旧UIKit、没有复用机制、内存泄漏、不支持暗黑模式
// ✅ iOS子代理会给你的专业方案
import SwiftUI
import Combine
// MARK: - 数据模型
@MainActor
finalclass ItemViewModel: ObservableObject {
@Publishedprivate(set) var items: [Item] = []
@Publishedprivate(set) var isLoading = false
@Publishedprivate(set) var error: Error?
privatevar cancellables = Set<AnyCancellable>()
privatelet repository: ItemRepository
init(repository: ItemRepository = .shared) {
self.repository = repository
setupBindings()
}
privatefunc setupBindings() {
// 自动保存到Core Data
$items
.debounce(for: .seconds(0.5), scheduler: RunLoop.main)
.sink { [weakself] items in
self?.repository.save(items)
}
.store(in: &cancellables)
}
@MainActor
func loadItems() async {
isLoading = true
error = nil
do {
// 并发加载本地和云端数据
async let localItems = repository.fetchLocal()
async let cloudItems = repository.fetchFromCloud()
// 合并数据源
let (local, cloud) = await (localItems, cloudItems)
self.items = mergeItems(local: local, cloud: cloud)
// 预加载图片缓存
await preloadImages(for: items)
} catch {
self.error = error
// 发送崩溃报告
CrashReporter.shared.log(error)
}
isLoading = false
}
privatefunc preloadImages(for items: [Item]) async {
await withTaskGroup(of: Void.self) { group in
for item in items {
group.addTask {
await ImageCache.shared.preload(item.imageURL)
}
}
}
}
}
// MARK: - SwiftUI视图
struct ItemListView: View {
@StateObjectprivatevar viewModel = ItemViewModel()
@Environment(\.horizontalSizeClass) var sizeClass
@AppStorage("listLayout") privatevar layout = ListLayout.grid
var body: some View {
NavigationStack {
Group {
if viewModel.isLoading {
ProgressView()
.progressViewStyle(.circular)
.scaleEffect(1.5)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} elseiflet error = viewModel.error {
ErrorView(error: error) {
Task { await viewModel.loadItems() }
}
} else {
itemContent
}
}
.navigationTitle("Items")
.navigationBarTitleDisplayMode(.large)
.toolbar { toolbarContent }
.refreshable { await viewModel.loadItems() }
.searchable(text: $viewModel.searchText)
.task { await viewModel.loadItems() }
}
}
@ViewBuilder
privatevar itemContent: some View {
if layout == .grid && sizeClass == .regular {
// iPad优化的网格布局
LazyVGrid(
columns: [GridItem(.adaptive(minimum: 200))],
spacing: 16
) {
ForEach(viewModel.items) { item in
ItemCard(item: item)
.contextMenu { contextMenuItems(for: item) }
}
}
.padding()
} else {
// iPhone优化的列表布局
List(viewModel.items) { item in
ItemRow(item: item)
.swipeActions(edge: .trailing) {
swipeActions(for: item)
}
.listRowInsets(EdgeInsets())
}
.listStyle(.insetGrouped)
}
}
@ToolbarContentBuilder
privatevar toolbarContent: some ToolbarContent {
ToolbarItem(placement: .navigationBarTrailing) {
Menu {
Picker("Layout", selection: $layout) {
Label("List", systemImage: "list.bullet")
.tag(ListLayout.list)
Label("Grid", systemImage: "square.grid.2x2")
.tag(ListLayout.grid)
}
.pickerStyle(.inline)
Section {
Button(action: { /* 排序逻辑 */ }) {
Label("Sort", systemImage: "arrow.up.arrow.down")
}
Button(action: { /* 过滤逻辑 */ }) {
Label("Filter", systemImage: "line.3.horizontal.decrease")
}
}
} label: {
Image(systemName: "ellipsis.circle")
}
}
}
}
// MARK: - 性能优化的图片缓存
actor ImageCache {
staticlet shared = ImageCache()
privatevar cache = NSCache<NSString, UIImage>()
privatevar loadingTasks = [URL: Task<UIImage?, Never>]()
init() {
cache.countLimit = 100
cache.totalCostLimit = 100 * 1024 * 1024// 100MB
// 监听内存警告
NotificationCenter.default.addObserver(
forName: UIApplication.didReceiveMemoryWarningNotification,
object: nil,
queue: .main
) { [weak cache] _in
cache?.removeAllObjects()
}
}
func image(for url: URL) async -> UIImage? {
// 检查缓存
iflet cached = cache.object(forKey: url.absoluteString asNSString) {
return cached
}
// 避免重复下载
iflet existingTask = loadingTasks[url] {
return await existingTask.value
}
// 创建新的下载任务
let task = Task<UIImage?, Never> {
guardlet (data, _) = try? await URLSession.shared.data(from: url),
let image = UIImage(data: data) else {
returnnil
}
// 存入缓存
cache.setObject(image, forKey: url.absoluteString asNSString, cost: data.count)
return image
}
loadingTasks[url] = task
let image = await task.value
loadingTasks[url] = nil
return image
}
}
痛点类型 | 具体问题 | 子代理解决方案 |
|---|---|---|
生态集成 | 不了解苹果框架 | 自动集成HealthKit、CloudKit等 |
性能问题 | 内存泄漏、卡顿 | ARC管理、GCD并发优化 |
UI规范 | 不符合HIG | 遵循人机界面指南 |
审核被拒 | 违反App Store规则 | 预检查审核要点 |
版本兼容 | 新旧系统适配 | 自动处理API可用性 |
iOS开发就像在苹果的"围墙花园"里种花:
iOS子代理帮你成为这个花园的园艺大师。
---
name: ios-developer
description: Develop native iOS applications using Swift, SwiftUI, and iOS frameworks. Specializes in Apple ecosystem integration, performance optimization, and App Store guidelines. Use PROACTIVELY for iOS-specific development and optimization.
model: sonnet
---
You are an iOS development expert specializing in creating exceptional native iOS applications using modern Swift and Apple frameworks.
## iOS Development Stack
- Swift 5.9+ with advanced language features and concurrency
- SwiftUI for declarative user interface development
- UIKit integration for complex custom interfaces
- Combine framework for reactive programming patterns
- Core Data and CloudKit for data persistence and sync
- Core Animation and Metal for high-performance graphics
- HealthKit, MapKit, and ARKit integration
- Push notifications with UserNotifications framework
## Apple Ecosystem Integration
1. iCloud synchronization and CloudKit implementation
2. Apple Pay integration for secure transactions
3. Siri Shortcuts and Intent handling
4. Apple Watch companion app development
5. iPad multitasking and adaptive layouts
6. macOS Catalyst for cross-platform compatibility
7. App Clips for lightweight experiences
8. Sign in with Apple for privacy-focused authentication
## Performance and Quality Standards
- Memory management with ARC and leak detection
- Grand Central Dispatch for concurrent programming
- Network optimization with URLSession and caching
- Image processing and Core Graphics optimization
- Battery life optimization and background processing
- Accessibility implementation with VoiceOver support
- Localization and internationalization best practices
- Unit testing with XCTest and UI testing automation
## App Store Excellence
- Human Interface Guidelines (HIG) compliance
- App Store Review Guidelines adherence
- App Store Connect integration and metadata optimization
- TestFlight beta testing and feedback collection
- App analytics with App Store Connect and third-party tools
- A/B testing implementation for feature optimization
- Crash reporting with Crashlytics or similar tools
- Performance monitoring with Instruments and Xcode
Build iOS applications that feel native and leverage the full power of Apple's ecosystem. Focus on performance, user experience, and seamless integration with iOS features while ensuring App Store approval.
---
name: ios-developer
description: 使用Swift、SwiftUI和iOS框架开发原生iOS应用。专精苹果生态集成、性能优化和App Store指南。在iOS开发和优化时主动使用。
model: sonnet
---
你是一位iOS开发专家,专精使用现代Swift和苹果框架创建卓越的原生iOS应用。
## iOS开发技术栈 / iOS Development Stack
- Swift 5.9+高级语言特性和并发编程
- SwiftUI声明式用户界面开发
- UIKit集成用于复杂自定义界面
- Combine框架响应式编程模式
- Core Data和CloudKit数据持久化和同步
- Core Animation和Metal高性能图形
- HealthKit、MapKit和ARKit集成
- UserNotifications框架推送通知
## 苹果生态集成 / Apple Ecosystem Integration
1. iCloud同步和CloudKit实现
2. Apple Pay安全交易集成
3. Siri快捷指令和Intent处理
4. Apple Watch配套应用开发
5. iPad多任务和自适应布局
6. macOS Catalyst跨平台兼容
7. App Clips轻量级体验
8. Sign in with Apple隐私认证
## 性能和质量标准 / Performance and Quality Standards
- ARC内存管理和泄漏检测
- Grand Central Dispatch并发编程
- URLSession网络优化和缓存
- Core Graphics图像处理优化
- 电池续航优化和后台处理
- VoiceOver无障碍支持
- 本地化和国际化最佳实践
- XCTest单元测试和UI自动化测试
## App Store卓越标准 / App Store Excellence
- 人机界面指南(HIG)合规
- App Store审核指南遵守
- App Store Connect集成和元数据优化
- TestFlight测试和反馈收集
- App Store Connect分析工具
- A/B测试功能优化
- Crashlytics崩溃报告
- Instruments性能监控
构建原生体验的iOS应用,充分利用苹果生态的全部能力。
专注于性能、用户体验和iOS功能的无缝集成,同时确保App Store审核通过。
// 1. 什么是SwiftUI?
// 就像搭积木,声明你想要什么,系统帮你实现
struct ContentView: View {
var body: some View {
Text("Hello") // 我要一个文本
.font(.title) // 标题大小
.foregroundColor(.blue) // 蓝色
}
}
// 2. 什么是Combine?
// 就像水管系统,数据像水一样流动
let publisher = Timer.publish(every: 1, on: .main, in: .common)
.autoconnect()
.map { _inDate() }
.sink { date in
print("当前时间: \(date)")
}
// 3. 什么是async/await?
// 就像点外卖,下单后可以做其他事,送到了再处理
func fetchData() async throws -> Data {
let (data, _) = try await URLSession.shared.data(from: url)
return data
}
// 4. 什么是ARC?
// 自动内存管理,像智能垃圾桶,自动清理不用的对象
class Person {
var name: String
deinit {
print("\(name) 被自动清理了")
}
}
# 在Claude Code中输入
/agents
选择上面的英文版或中文版配置,完整粘贴
iOS开发需要的权限:
建议选择 🔵 蓝色(iOS的标志色),保存配置
输入指令:
创建一个天气应用,要支持定位、Widget和Apple Watch
iOS子代理会输出完整的项目结构和核心代码(这里展示关键部分):
// WeatherApp.swift - 主应用入口
import SwiftUI
@main
struct WeatherApp: App {
@StateObjectprivatevar weatherManager = WeatherManager()
@StateObjectprivatevar locationManager = LocationManager()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(weatherManager)
.environmentObject(locationManager)
.onAppear {
setupApp()
}
}
}
privatefunc setupApp() {
// 请求位置权限
locationManager.requestPermission()
// 注册后台任务
BGTaskScheduler.shared.register(
forTaskWithIdentifier: "com.app.weather.refresh",
using: nil
) { task in
handleBackgroundRefresh(task as! BGAppRefreshTask)
}
}
}
// WeatherWidget.swift - Widget实现
import WidgetKit
import SwiftUI
struct WeatherWidget: Widget {
let kind: String = "WeatherWidget"
var body: some WidgetConfiguration {
IntentConfiguration(
kind: kind,
intent: ConfigurationIntent.self,
provider: Provider()
) { entry in
WeatherWidgetView(entry: entry)
}
.configurationDisplayName("天气")
.description("显示当前天气信息")
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}
输入:
创建一个支持滤镜、手势操作的图片编辑器
iOS子代理输出的核心功能:
// PhotoEditor.swift - 高性能图片编辑器
import SwiftUI
import CoreImage
import Metal
@MainActor
class PhotoEditorViewModel: ObservableObject {
@Publishedvar originalImage: UIImage?
@Publishedvar processedImage: UIImage?
@Publishedvar currentFilter: CIFilter?
privatelet context: CIContext
privatelet metalDevice: MTLDevice?
init() {
// 使用Metal加速
self.metalDevice = MTLCreateSystemDefaultDevice()
self.context = CIContext(mtlDevice: metalDevice!)
}
func applyFilter(_ filterName: String, intensity: Double) async {
guardlet inputImage = originalImage,
let ciImage = CIImage(image: inputImage) else { return }
await Task.detached(priority: .userInitiated) {
letfilter = CIFilter(name: filterName)
filter?.setValue(ciImage, forKey: kCIInputImageKey)
filter?.setValue(intensity, forKey: kCIInputIntensityKey)
iflet outputImage = filter?.outputImage,
let cgImage = self.context.createCGImage(outputImage, from: outputImage.extent) {
let processedUIImage = UIImage(cgImage: cgImage)
await MainActor.run {
self.processedImage = processedUIImage
}
}
}.value
}
}
游戏开发版:
## iOS Development Stack
- SpriteKit 2D游戏引擎
- SceneKit 3D图形
- GameplayKit AI和逻辑
- GameCenter集成
- Metal性能着色器
企业应用版:
## iOS Development Stack
- MDM配置支持
- 企业证书管理
- VPN集成
- 单点登录(SSO)
- 离线数据同步
## Team Standards
-代码风格:SwiftAPIDesignGuidelines
-架构模式:MVVM+Coordinator
-依赖管理:SwiftPackageManager
-最低系统:iOS15.0
-设备支持:iPhone、iPad通用
触发关键词:
子代理会自动使用可用性检查:
if #available(iOS 16.0, *) {
// iOS 16新特性
NavigationStack { }
} else {
// 旧版本兼容
NavigationView { }
}
子代理会自动实现:
自动检查:
评估指标 | 通用Claude | iOS子代理 | 提升幅度 |
|---|---|---|---|
代码规范 | 45% | 98% | +118% |
性能优化 | 30% | 95% | +217% |
生态集成 | 25% | 92% | +268% |
审核通过率 | 60% | 95% | +58% |
用户体验 | 50% | 96% | +92% |
这个iOS开发子代理带来的价值:
记住:iOS开发不只是写代码,更是创造符合苹果设计哲学的精品应用。这个子代理帮你成为真正的iOS工匠。
/agents 创建代理现在就配置你的iOS开发子代理,让每个App都达到App Store精选标准!🍎📱
#子代理 #ClaudeCode #AI #程序员 #前端达人