sentry-ios-swift-setup
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSentry iOS Swift Setup
Sentry iOS Swift 安装与配置
Install and configure Sentry in iOS projects using Swift and SwiftUI.
在使用Swift和SwiftUI的iOS项目中安装并配置Sentry。
Invoke This Skill When
适用场景
- User asks to "add Sentry to iOS" or "install Sentry" in a Swift app
- User wants error monitoring, tracing, or session replay in iOS
- User mentions "sentry-cocoa" or iOS crash reporting
Important: The configuration options and code samples below are examples. Always verify against docs.sentry.io before implementing, as APIs and defaults may have changed.
- 当用户询问“为iOS添加Sentry”或在Swift应用中“安装Sentry”时
- 当用户需要iOS应用的错误监控、追踪或会话重放功能时
- 当用户提到“sentry-cocoa”或iOS崩溃报告时
重要提示:以下配置选项和代码示例仅供参考。在实施前请务必对照docs.sentry.io进行验证,因为API和默认设置可能已更新。
Requirements
系统要求
- iOS 15.0+, macOS 12.0+, tvOS 15.0+, watchOS 8.0+
- iOS 15.0+、macOS 12.0+、tvOS 15.0+、watchOS 8.0+
Install
安装
Swift Package Manager (Recommended)
Swift Package Manager(推荐)
- File > Add Package Dependencies
- Enter:
https://github.com/getsentry/sentry-cocoa.git - Select version rule: "Up to Next Major" from
9.5.0
SPM Products: Choose based on your needs:
| Product | Use Case |
|---|---|
| Default (static linking) |
| Dynamic framework |
| SwiftUI view performance tracking |
| App extensions or CLI tools |
- 点击 File > Add Package Dependencies
- 输入:
https://github.com/getsentry/sentry-cocoa.git - 选择版本规则:从开始“Up to Next Major”(兼容下一个大版本)
9.5.0
SPM产品选择:根据需求选择:
| 产品 | 使用场景 |
|---|---|
| 默认选项(静态链接) |
| 动态框架 |
| SwiftUI视图性能追踪 |
| 应用扩展或CLI工具 |
CocoaPods
CocoaPods
ruby
undefinedruby
undefinedPodfile
Podfile
pod 'Sentry', :git => 'https://github.com/getsentry/sentry-cocoa.git', :tag => '9.5.0'
Then run `pod install`.pod 'Sentry', :git => 'https://github.com/getsentry/sentry-cocoa.git', :tag => '9.5.0'
然后运行 `pod install`.Configure
配置
SwiftUI App
SwiftUI应用
swift
import SwiftUI
import Sentry
@main
struct YourApp: App {
init() {
SentrySDK.start { options in
options.dsn = "YOUR_SENTRY_DSN"
options.debug = true
// Tracing
options.tracesSampleRate = 1.0
// Profiling
options.configureProfiling = {
$0.sessionSampleRate = 1.0
$0.lifecycle = .trace
}
// Session Replay
options.sessionReplay.sessionSampleRate = 1.0
options.sessionReplay.onErrorSampleRate = 1.0
// Logs (SDK 9.0.0+; for 8.55.0-8.x use options.experimental.enableLogs)
options.enableLogs = true
// Error context
options.attachScreenshot = true
options.attachViewHierarchy = true
}
}
var body: some Scene {
WindowGroup { ContentView() }
}
}swift
import SwiftUI
import Sentry
@main
struct YourApp: App {
init() {
SentrySDK.start { options in
options.dsn = "YOUR_SENTRY_DSN"
options.debug = true
// 追踪配置
options.tracesSampleRate = 1.0
// 性能分析
options.configureProfiling = {
$0.sessionSampleRate = 1.0
$0.lifecycle = .trace
}
// 会话重放
options.sessionReplay.sessionSampleRate = 1.0
options.sessionReplay.onErrorSampleRate = 1.0
// 日志配置(SDK 9.0.0+;8.55.0-8.x版本请使用options.experimental.enableLogs)
options.enableLogs = true
// 错误上下文
options.attachScreenshot = true
options.attachViewHierarchy = true
}
}
var body: some Scene {
WindowGroup { ContentView() }
}
}UIKit App
UIKit应用
swift
import UIKit
import Sentry
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
SentrySDK.start { options in
options.dsn = "YOUR_SENTRY_DSN"
options.debug = true
options.tracesSampleRate = 1.0
options.enableLogs = true
}
return true
}
}swift
import UIKit
import Sentry
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
SentrySDK.start { options in
options.dsn = "YOUR_SENTRY_DSN"
options.debug = true
options.tracesSampleRate = 1.0
options.enableLogs = true
}
return true
}
}Configuration Options
配置选项
| Option | Description | Default |
|---|---|---|
| Sentry DSN | Required |
| % of transactions traced | |
| % of sessions replayed | |
| % of error sessions replayed | |
| Send logs to Sentry | |
| Attach screenshot on error | |
| Attach view hierarchy on error | |
| 选项 | 说明 | 默认值 |
|---|---|---|
| Sentry DSN(必填项) | 无 |
| 被追踪的事务占比 | |
| 被重放的会话占比 | |
| 发生错误时被重放的会话占比 | |
| 向Sentry发送日志 | |
| 错误发生时附带截图 | |
| 错误发生时附带视图层级 | |
Auto-Instrumented Features
自动埋点功能
| Feature | What's Captured |
|---|---|
| App Launches | Cold/warm start times |
| Network | URLSession requests |
| UI | UIViewController loads, user interactions |
| File I/O | Read/write operations |
| Core Data | Fetch/save operations |
| Frames | Slow and frozen frame detection |
| 功能 | 捕获内容 |
|---|---|
| 应用启动 | 冷启动/热启动耗时 |
| 网络请求 | URLSession请求 |
| UI交互 | UIViewController加载、用户操作 |
| 文件I/O | 读写操作 |
| Core Data | 读取/保存操作 |
| 帧检测 | 慢帧和冻结帧检测 |
Logging
日志记录
swift
let logger = SentrySDK.logger
logger.info("User action", attributes: [
"userId": "123",
"action": "checkout"
])
// Log levels: trace, debug, info, warn, error, fatalswift
let logger = SentrySDK.logger
logger.info("User action", attributes: [
"userId": "123",
"action": "checkout"
])
// 日志级别: trace, debug, info, warn, error, fatalSession Replay
会话重放
iOS 26+ / Xcode 26+ caveat: SDK 8.57.0+ automatically disables Session Replay on iOS 26.0+ when built with Xcode 26.0+ due to Apple's Liquid Glass rendering breaking masking reliability. Replay still works on iOS < 26 or Xcode < 26. To force-enable (use with caution): .
options.experimental.enableSessionReplayInUnreliableEnvironment = trueiOS 26+ / Xcode 26+ 注意事项:由于Apple的Liquid Glass渲染会破坏遮罩可靠性,使用Xcode 26.0+构建的SDK 8.57.0+会自动在iOS 26.0+上禁用会话重放。在iOS <26或Xcode <26环境下重放功能仍可正常使用。如需强制启用(请谨慎使用):。
options.experimental.enableSessionReplayInUnreliableEnvironment = trueMasking
内容遮罩
swift
// SwiftUI modifiers
Text("Safe content").sentryReplayUnmask()
Text(user.email).sentryReplayMask()swift
// SwiftUI修饰符
Text("Safe content").sentryReplayUnmask()
Text(user.email).sentryReplayMask()User Context
用户上下文
swift
let user = User()
user.userId = "user_123"
user.email = "user@example.com"
SentrySDK.setUser(user)
// Clear on logout
SentrySDK.setUser(nil)swift
let user = User()
user.userId = "user_123"
user.email = "user@example.com"
SentrySDK.setUser(user)
// 登出时清除用户信息
SentrySDK.setUser(nil)Verification
验证配置
swift
// Test error capture
SentrySDK.capture(message: "Test from iOS")
// Or trigger a test error
do {
try someFailingFunction()
} catch {
SentrySDK.capture(error: error)
}swift
// 测试错误捕获
SentrySDK.capture(message: "Test from iOS")
// 或触发测试错误
do {
try someFailingFunction()
} catch {
SentrySDK.capture(error: error)
}Production Settings
生产环境配置
swift
SentrySDK.start { options in
options.dsn = "YOUR_SENTRY_DSN"
options.debug = false
options.tracesSampleRate = 0.2 // 20%
options.sessionReplay.sessionSampleRate = 0.1 // 10%
options.sessionReplay.onErrorSampleRate = 1.0 // 100% on error
options.enableLogs = true
}swift
SentrySDK.start { options in
options.dsn = "YOUR_SENTRY_DSN"
options.debug = false
options.tracesSampleRate = 0.2 // 20%
options.sessionReplay.sessionSampleRate = 0.1 // 10%
options.sessionReplay.onErrorSampleRate = 1.0 // 错误时100%重放
options.enableLogs = true
}Size Analysis (Fastlane)
包大小分析(Fastlane)
Track app bundle size with Sentry using the Fastlane plugin.
使用Fastlane插件通过Sentry追踪应用包大小。
Install Plugin
安装插件
bash
bundle exec fastlane add_plugin fastlane-plugin-sentrybash
bundle exec fastlane add_plugin fastlane-plugin-sentryConfigure Authentication
配置认证
bash
undefinedbash
undefinedEnvironment variable (recommended for CI)
环境变量(CI环境推荐)
export SENTRY_AUTH_TOKEN=your_token_here
Or create `.sentryclirc` (add to `.gitignore`):
```ini
[auth]
token=YOUR_SENTRY_AUTH_TOKENexport SENTRY_AUTH_TOKEN=your_token_here
或创建 `.sentryclirc` 文件(需添加到 `.gitignore`):
```ini
[auth]
token=YOUR_SENTRY_AUTH_TOKENFastfile Lane
Fastfile 任务
ruby
lane :sentry_size do
build_app(
scheme: "YourApp",
configuration: "Release",
export_method: "app-store"
)
sentry_upload_build(
org_slug: "your-org",
project_slug: "your-project",
build_configuration: "Release"
)
endruby
lane :sentry_size do
build_app(
scheme: "YourApp",
configuration: "Release",
export_method: "app-store"
)
sentry_upload_build(
org_slug: "your-org",
project_slug: "your-project",
build_configuration: "Release"
)
endRun Size Analysis
运行包大小分析
bash
bundle exec fastlane sentry_sizeView results in the Sentry UI after the upload completes.
bash
bundle exec fastlane sentry_size上传完成后,可在Sentry UI中查看分析结果。
Troubleshooting
故障排查
| Issue | Solution |
|---|---|
| Events not appearing | Check DSN, enable |
| No traces | Set |
| No replays | Set |
| No logs | Set |
| CocoaPods fails | Run |
| Size upload fails | Check |
| 问题 | 解决方案 |
|---|---|
| 事件未显示 | 检查DSN是否正确,启用 |
| 无追踪数据 | 设置 |
| 无重放内容 | 设置 |
| 无日志数据 | SDK 9.0.0+版本设置 |
| CocoaPods安装失败 | 运行 |
| 包大小上传失败 | 检查 |