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
- 当用户询问“在iOS中添加Sentry”或“在Swift应用中安装Sentry”时
- 当用户需要为iOS应用实现错误监控、链路追踪或会话重放时
- 当用户提及“sentry-cocoa”或iOS崩溃上报时
Requirements
系统要求
- iOS 13.0+
- Xcode 15.0+
- Swift 5.0+
- iOS 13.0+
- Xcode 15.0+
- Swift 5.0+
Install
安装步骤
Swift Package Manager (Recommended)
Swift Package Manager(推荐)
- File > Add Package Dependencies
- Enter:
https://github.com/getsentry/sentry-cocoa - Select version rule: "Up to Next Major" from
9.0.0
- 点击File > Add Package Dependencies
- 输入:
https://github.com/getsentry/sentry-cocoa - 选择版本规则:从开始的“Up to Next Major”
9.0.0
CocoaPods
CocoaPods
ruby
undefinedruby
undefinedPodfile
Podfile
pod 'Sentry', '~> 9.0'
Then run `pod install`.pod 'Sentry', '~> 9.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
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
// 日志上报
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 | Screen loads, transitions |
| File I/O | Read/write operations |
| Core Data | Fetch/save operations |
| App Hangs | Main thread blocking |
| 功能 | 捕获内容 |
|---|---|
| 应用启动 | 冷启动/热启动耗时 |
| 网络请求 | URLSession 请求 |
| UI 交互 | 页面加载、页面跳转 |
| 文件操作 | 读/写操作 |
| 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 Masking
会话重放脱敏
swift
// SwiftUI modifiers
Text("Safe content").sentryReplayUnmask()
Text(user.email).sentryReplayMask()
// Debug masking in development
#if DEBUG
SentrySDK.replay.showMaskPreview()
#endifswift
// SwiftUI 修饰符
Text("Safe content").sentryReplayUnmask()
Text(user.email).sentryReplayMask()
// 开发环境下调试脱敏效果
#if DEBUG
SentrySDK.replay.showMaskPreview()
#endifUser 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")
// Test crash (dev only)
SentrySDK.crash()swift
// 测试错误捕获
SentrySDK.capture(message: "Test from iOS")
// 测试崩溃(仅开发环境)
SentrySDK.crash()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
安装插件
ruby
undefinedruby
undefinedfastlane/Pluginfile
fastlane/Pluginfile
gem 'fastlane-plugin-sentry'
Then run `bundle install`.gem 'fastlane-plugin-sentry'
然后运行`bundle install`。Configure 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 Sentry: Settings > Size Analysis
bash
bundle exec fastlane sentry_size在Sentry中查看结果:设置 > 包大小分析
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 |
| 问题 | 解决方案 |
|---|---|
| 事件未出现在Sentry中 | 检查DSN是否正确,开启 |
| 无链路追踪数据 | 设置 |
| 无会话重放数据 | 设置 |
| 无日志数据 | 设置 |
| CocoaPods安装失败 | 运行 |
| 包大小分析上传失败 | 检查 |