sentry-ios-swift-setup

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Sentry 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(推荐)

  1. File > Add Package Dependencies
  2. Enter:
    https://github.com/getsentry/sentry-cocoa
  3. Select version rule: "Up to Next Major" from
    9.0.0
  1. 点击File > Add Package Dependencies
  2. 输入:
    https://github.com/getsentry/sentry-cocoa
  3. 选择版本规则:从
    9.0.0
    开始的“Up to Next Major”

CocoaPods

CocoaPods

ruby
undefined
ruby
undefined

Podfile

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

配置选项

OptionDescriptionDefault
dsn
Sentry DSNRequired
tracesSampleRate
% of transactions traced
0
sessionReplay.sessionSampleRate
% of sessions replayed
0
sessionReplay.onErrorSampleRate
% of error sessions replayed
0
enableLogs
Send logs to Sentry
false
attachScreenshot
Attach screenshot on error
false
attachViewHierarchy
Attach view hierarchy on error
false
选项说明默认值
dsn
Sentry DSN(必填)
tracesSampleRate
链路追踪的事务采样率
0
sessionReplay.sessionSampleRate
会话重放的采样率
0
sessionReplay.onErrorSampleRate
错误会话的重放采样率
0
enableLogs
是否向Sentry上报日志
false
attachScreenshot
错误发生时是否附带截图
false
attachViewHierarchy
错误发生时是否附带视图层级
false

Auto-Instrumented Features

自动埋点功能

FeatureWhat's Captured
App LaunchesCold/warm start times
NetworkURLSession requests
UIScreen loads, transitions
File I/ORead/write operations
Core DataFetch/save operations
App HangsMain 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, fatal
swift
let logger = SentrySDK.logger

logger.info("User action", attributes: [
    "userId": "123",
    "action": "checkout"
])

// 日志级别:trace, debug, info, warn, error, fatal

Session Replay Masking

会话重放脱敏

swift
// SwiftUI modifiers
Text("Safe content").sentryReplayUnmask()
Text(user.email).sentryReplayMask()

// Debug masking in development
#if DEBUG
SentrySDK.replay.showMaskPreview()
#endif
swift
// SwiftUI 修饰符
Text("Safe content").sentryReplayUnmask()
Text(user.email).sentryReplayMask()

// 开发环境下调试脱敏效果
#if DEBUG
SentrySDK.replay.showMaskPreview()
#endif

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")

// 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
undefined
ruby
undefined

fastlane/Pluginfile

fastlane/Pluginfile

gem 'fastlane-plugin-sentry'

Then run `bundle install`.
gem 'fastlane-plugin-sentry'

然后运行`bundle install`。

Configure Authentication

配置认证信息

bash
undefined
bash
undefined

Environment variable (recommended for CI)

环境变量(CI环境推荐)

export SENTRY_AUTH_TOKEN=your_token_here

Or create `.sentryclirc` (add to `.gitignore`):

```ini
[auth]
token=YOUR_SENTRY_AUTH_TOKEN
export SENTRY_AUTH_TOKEN=your_token_here

或创建`.sentryclirc`文件(需添加到`.gitignore`):

```ini
[auth]
token=YOUR_SENTRY_AUTH_TOKEN

Fastfile 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"
  )
end
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"
  )
end

Run Size Analysis

运行包大小分析

bash
bundle exec fastlane sentry_size
View results in Sentry: Settings > Size Analysis
bash
bundle exec fastlane sentry_size
在Sentry中查看结果:设置 > 包大小分析

Troubleshooting

问题排查

IssueSolution
Events not appearingCheck DSN, enable
debug = true
No tracesSet
tracesSampleRate
> 0
No replaysSet
sessionSampleRate
> 0, check SDK 8.0+
No logsSet
enableLogs = true
, check SDK 8.55+
CocoaPods failsRun
pod repo update
, check iOS 13+ target
Size upload failsCheck
SENTRY_AUTH_TOKEN
, verify org/project slugs
问题解决方案
事件未出现在Sentry中检查DSN是否正确,开启
debug = true
排查
无链路追踪数据设置
tracesSampleRate
大于0
无会话重放数据设置
sessionSampleRate
大于0,检查SDK版本是否为8.0+
无日志数据设置
enableLogs = true
,检查SDK版本是否为8.55+
CocoaPods安装失败运行
pod repo update
,检查目标iOS版本是否为13+
包大小分析上传失败检查
SENTRY_AUTH_TOKEN
是否有效,验证组织/项目Slug是否正确