macos-developer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesemacOS Developer
macOS 开发者
Purpose
用途
Provides native macOS application development expertise specializing in AppKit, SwiftUI for Mac, and system integration. Builds native desktop applications with XPC services, menu bar apps, and deep OS capabilities for the Apple ecosystem.
提供专注于AppKit、SwiftUI for Mac和系统集成的原生macOS应用开发技术支持,为苹果生态系统构建具备XPC服务、菜单栏应用以及深度系统功能的原生桌面应用。
When to Use
适用场景
- Building native macOS apps (DMG/App Store)
- Developing Menu Bar apps (NSStatusItem)
- Implementing XPC Services for privilege separation
- Creating System Extensions (Endpoint Security, Network Extension)
- Porting iPad apps to Mac (Catalyst)
- Automating Mac admin tasks (AppleScript/JXA)
- 构建原生macOS应用(DMG/应用商店版本)
- 开发菜单栏应用(NSStatusItem)
- 实现用于权限分离的XPC服务
- 创建系统扩展(终端安全、网络扩展)
- 将iPad应用迁移至Mac(Catalyst)
- 自动化Mac管理任务(AppleScript/JXA)
2. Decision Framework
2. 决策框架
UI Framework
UI框架
| Framework | Best For | Pros | Cons |
|---|---|---|---|
| SwiftUI | Modern Apps | Declarative, simple code. | Limited AppKit feature parity. |
| AppKit | System Tools | Full control (NSWindow, NSView). | Imperative, verbose. |
| Catalyst | iPad Ports | Free Mac app from iPad code. | Looks like an iPad app. |
| 框架 | 适用场景 | 优势 | 劣势 |
|---|---|---|---|
| SwiftUI | 现代应用 | 声明式语法,代码简洁。 | AppKit功能支持有限。 |
| AppKit | 系统工具 | 完全控制(NSWindow、NSView)。 | 命令式语法,代码冗长。 |
| Catalyst | iPad应用迁移 | 基于iPad代码快速生成Mac应用。 | 外观与iPad应用类似。 |
Distribution Channel
分发渠道
- Mac App Store: Sandboxed, verified, easy updates. (Required for System Extensions).
- Direct Distribution (DMG): Notarization required. More freedom (Accessibility API, Full Disk Access).
- Mac应用商店: 沙箱环境、经过验证、更新便捷。(系统扩展必须通过此渠道分发)
- 直接分发(DMG): 需要公证,拥有更多自由度(可访问辅助功能API、全磁盘访问权限)。
Process Architecture
进程架构
- Monolith: Simple apps.
- XPC Service: Complex apps. Isolates crashes, allows privilege escalation (Helper tool).
Red Flags → Escalate to :
security-engineer- Requesting "Full Disk Access" without a valid reason
- Embedding private keys in the binary
- Bypassing Gatekeeper/Notarization
- 单体架构: 适用于简单应用。
- XPC服务: 适用于复杂应用,可隔离崩溃、支持权限提升(辅助工具)。
风险预警 → 需转交至处理:
security-engineer- 无合理理由请求"全磁盘访问"权限
- 在二进制文件中嵌入私钥
- 绕过Gatekeeper/公证机制
3. Core Workflows
3. 核心工作流程
Workflow 1: Menu Bar App (SwiftUI)
工作流程1:SwiftUI菜单栏应用
Goal: Create an app that lives in the menu bar.
Steps:
-
App Setupswift
@main struct MenuBarApp: App { var body: some Scene { MenuBarExtra("Utility", systemImage: "hammer") { Button("Action") { doWork() } Divider() Button("Quit") { NSApplication.shared.terminate(nil) } } } } -
Hide Dock Icon
- Info.plist: =
LSUIElement.YES
- Info.plist:
目标: 创建一个常驻菜单栏的应用。
步骤:
-
应用设置swift
@main struct MenuBarApp: App { var body: some Scene { MenuBarExtra("Utility", systemImage: "hammer") { Button("Action") { doWork() } Divider() Button("Quit") { NSApplication.shared.terminate(nil) } } } } -
隐藏程序坞图标
- 在Info.plist中设置=
LSUIElement。YES
- 在Info.plist中设置
Workflow 3: System Extension (Endpoint Security)
工作流程3:终端安全系统扩展
Goal: Monitor file events.
Steps:
-
Entitlements
- =
com.apple.developer.endpoint-security.client.YES
-
Implementation (C API)c
es_client_t *client; es_new_client(&client, ^(es_client_t *c, const es_message_t *msg) { if (msg->event_type == ES_EVENT_TYPE_NOTIFY_EXEC) { // Log process execution } });
目标: 监控文件事件。
步骤:
-
权限配置
- 设置=
com.apple.developer.endpoint-security.client。YES
- 设置
-
实现(C API)c
es_client_t *client; es_new_client(&client, ^(es_client_t *c, const es_message_t *msg) { if (msg->event_type == ES_EVENT_TYPE_NOTIFY_EXEC) { // Log process execution } });
5. Anti-Patterns & Gotchas
5. 反模式与注意事项
❌ Anti-Pattern 1: Assuming iOS Behavior
❌ 反模式1:照搬iOS行为
What it looks like:
- Using (split view) when a simple Window is needed.
NavigationView - Ignoring Menu Bar commands (,
Cmd+Q).Cmd+S
Why it fails:
- Feels alien on Mac.
Correct approach:
- Support Keyboard Shortcuts.
- Support Multi-Window workflows.
表现:
- 仅需简单窗口时使用(分栏视图)
NavigationView - 忽略菜单栏命令(、
Cmd+Q)Cmd+S
问题:
- 在Mac平台上体验违和
正确做法:
- 支持键盘快捷键
- 支持多窗口工作流
❌ Anti-Pattern 2: Blocking Main Thread
❌ 反模式2:阻塞主线程
What it looks like:
- Running file I/O on main thread.
Why it fails:
- Spinning Beach Ball of Death (SPOD).
Correct approach:
- Use or Swift
DispatchQueue.global().Task
表现:
- 在主线程中执行文件I/O操作
问题:
- 出现"沙滩球"卡顿(SPOD)
正确做法:
- 使用或Swift
DispatchQueue.global()Task
Examples
示例
Example 1: Professional Menu Bar Application
示例1:专业级菜单栏应用
Scenario: Build a system utility that lives in the macOS menu bar for quick access.
Development Approach:
- Project Setup: SwiftUI with MenuBarExtra
- Window Management: Hidden dock icon with popup menu
- Settings Integration: UserDefaults for preferences
- Status Item: Custom NSStatusItem with icon and menu
Implementation:
swift
@main
struct SystemUtilityApp: App {
var body: some Scene {
MenuBarExtra("System Utility", systemImage: "gear") {
VStack(spacing: 12) {
Button("Open Preferences") { openPreferences() }
Button("Check Updates") { checkForUpdates() }
Divider()
Button("Quit") { NSApplication.shared.terminate(nil) }
}
.padding()
.frame(width: 200)
}
}
}Key Features:
- LSUIElement in Info.plist to hide dock icon
- Keyboard shortcuts for quick actions
- Background refresh with menu updates
- Sparkle for automatic updates
Results:
- Released on Mac App Store with 4.8-star rating
- 50,000+ active users
- Featured in "Best New Apps" category
场景: 构建一个常驻macOS菜单栏的系统工具,方便快速访问。
开发方案:
- 项目设置:使用SwiftUI的MenuBarExtra
- 窗口管理:隐藏程序坞图标,搭配弹出菜单
- 设置集成:使用UserDefaults存储偏好设置
- 状态项:自定义NSStatusItem,包含图标和菜单
实现代码:
swift
@main
struct SystemUtilityApp: App {
var body: some Scene {
MenuBarExtra("System Utility", systemImage: "gear") {
VStack(spacing: 12) {
Button("Open Preferences") { openPreferences() }
Button("Check Updates") { checkForUpdates() }
Divider()
Button("Quit") { NSApplication.shared.terminate(nil) }
}
.padding()
.frame(width: 200)
}
}
}核心功能:
- 在Info.plist中设置LSUIElement以隐藏程序坞图标
- 为快速操作配置键盘快捷键
- 后台刷新并更新菜单
- 使用Sparkle实现自动更新
成果:
- 在Mac应用商店发布,获得4.8星评分
- 50,000+活跃用户
- 入选"最佳新应用"分类
Example 2: Document-Based Application with XPC Services
示例2:基于XPC服务的文档类应用
Scenario: Build a professional document editor with background processing.
Architecture:
- Main App: SwiftUI document handling
- XPC Service: Background document processing
- Sandbox: Proper app sandbox configuration
- IPC: NSXPCConnection for communication
XPC Service Implementation:
swift
// Service Protocol
@objc protocol ProcessingServiceProtocol {
func processDocument(at url: URL, reply: @escaping (URL?) -> Void)
}
// Service Implementation
class ProcessingService: NSObject, ProcessingServiceProtocol {
func processDocument(at url: URL, reply: @escaping (URL?) -> Void) {
// Heavy processing in separate process
let result = heavyProcessing(url: url)
reply(result)
}
}Benefits:
- Crash isolation (service crash doesn't kill app)
- Reduced memory footprint
- Privilege separation for sensitive operations
- Better App Store approval chances
场景: 构建具备后台处理能力的专业文档编辑器。
架构:
- 主应用:SwiftUI文档处理
- XPC服务:后台文档处理
- 沙箱:合理配置应用沙箱
- 进程间通信:使用NSXPCConnection进行通信
XPC服务实现代码:
swift
// 服务协议
@objc protocol ProcessingServiceProtocol {
func processDocument(at url: URL, reply: @escaping (URL?) -> Void)
}
// 服务实现
class ProcessingService: NSObject, ProcessingServiceProtocol {
func processDocument(at url: URL, reply: @escaping (URL?) -> Void) {
// 在独立进程中执行繁重处理
let result = heavyProcessing(url: url)
reply(result)
}
}优势:
- 崩溃隔离(服务崩溃不会导致主应用退出)
- 降低内存占用
- 敏感操作的权限分离
- 提高应用商店审核通过率
Example 3: System Extension for Network Monitoring
示例3:用于网络监控的系统扩展
Scenario: Create a network monitoring tool using System Extension.
Development Process:
- Entitlement Configuration: Endpoint security entitlement
- System Extension: Network extension implementation
- Deployment: Proper notarization and signing
- User Approval: System extension approval workflow
Implementation:
swift
// Network extension handler
class NetworkExtensionHandler: NEProvider {
override func startProtocol(options: [String: Any]?, completionHandler: @escaping (Error?) -> Void) {
// Start network monitoring
setupNetworkMonitoring()
completionHandler(nil)
}
override func stopProtocol(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
// Clean up resources
stopNetworkMonitoring()
completionHandler()
}
}Requirements:
- Notarization for distribution outside App Store
- User-approved system extension
- Proper entitlements from Apple Developer portal
场景: 使用系统扩展创建网络监控工具。
开发流程:
- 权限配置:配置终端安全权限
- 系统扩展:实现网络扩展
- 部署:完成公证和签名
- 用户授权:处理系统扩展的用户授权流程
实现代码:
swift
// 网络扩展处理器
class NetworkExtensionHandler: NEProvider {
override func startProtocol(options: [String: Any]?, completionHandler: @escaping (Error?) -> Void) {
// 启动网络监控
setupNetworkMonitoring()
completionHandler(nil)
}
override func stopProtocol(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
// 清理资源
stopNetworkMonitoring()
completionHandler()
}
}要求:
- 应用商店外分发需经过公证
- 需用户授权系统扩展
- 从Apple开发者平台获取合法权限
Best Practices
最佳实践
AppKit and SwiftUI Integration
AppKit与SwiftUI集成
- Hybrid Approach: Use SwiftUI for UI, AppKit for complex components
- NSViewRepresentable: Wrap NSView for SwiftUI use
- NSHostingView: Embed SwiftUI in AppKit windows
- Data Flow: Use Observable or StateObject for shared state
- 混合方案:使用SwiftUI构建UI,AppKit处理复杂组件
- NSViewRepresentable:将NSView封装后在SwiftUI中使用
- NSHostingView:在AppKit窗口中嵌入SwiftUI内容
- 数据流:使用Observable或StateObject管理共享状态
Sandboxing and Security
沙箱与安全
- Minimal Entitlements: Request only necessary permissions
- Keychain: Use Keychain for sensitive data storage
- App Sandbox: Enable for App Store distribution
- Hardened Runtime: Required for notarization
- 最小权限原则:仅请求必要的权限
- 钥匙串:使用Keychain存储敏感数据
- 应用沙箱:应用商店分发需启用
- 强化运行时:公证必须启用此功能
Distribution and Deployment
分发与部署
- Code Signing: Always sign before notarization
- Notarization: Submit to Apple for security validation
- Auto-Updates: Implement Sparkle for direct distribution
- DMG Creation: Use create-dmg or similar tools
- 代码签名:公证前必须完成签名
- 公证:提交至Apple进行安全验证
- 自动更新:直接分发应用使用Sparkle实现
- DMG制作:使用create-dmg或类似工具
Performance Optimization
性能优化
- Lazy Loading: Defer resource loading until needed
- Background Tasks: Use BGTaskScheduler for long operations
- Memory Management: Monitor memory pressure
- Startup Time: Optimize launch sequence
- 懒加载:延迟资源加载至需要时
- 后台任务:使用BGTaskScheduler执行长时间操作
- 内存管理:监控内存压力
- 启动时间:优化启动流程
User Experience
用户体验
- Keyboard Navigation: Support full keyboard operation
- Dark Mode: Properly handle light and dark appearances
- Accessibility: VoiceOver compatibility from start
- Window Management: Support multiple windows properly
- 键盘导航:支持全键盘操作
- 深色模式:适配明暗两种外观
- 无障碍支持:从开发初期兼容VoiceOver
- 窗口管理:完善支持多窗口
Quality Checklist
质量检查清单
UX:
- Menus: App supports standard menu commands.
- Windows: Resizable, supports Full Screen.
- Dark Mode: Supports System Appearance.
- Accessibility: VoiceOver works on key elements.
System:
- Sandboxing: App Sandbox enabled (if App Store).
- Hardened Runtime: Enabled for Notarization.
- Code Signing: Properly signed for distribution.
- Notarization: Submitted and approved by Apple.
Performance:
- Startup: App launches within 5 seconds.
- Memory: No memory leaks or excessive usage.
- Responsive: UI remains responsive during operations.
用户体验:
- 菜单: 应用支持标准菜单命令。
- 窗口: 可调整大小,支持全屏模式。
- 深色模式: 适配系统外观。
- 无障碍: 核心元素支持VoiceOver。
系统适配:
- 沙箱: 应用商店版本已启用应用沙箱。
- 强化运行时: 已启用以支持公证。
- 代码签名: 已完成分发所需的正确签名。
- 公证: 已提交并通过Apple审核。
性能:
- 启动速度: 应用在5秒内完成启动。
- 内存: 无内存泄漏或过度占用。
- 响应性: 操作过程中UI保持响应。