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

  1. File > Add Package Dependencies
  2. Enter:
    https://github.com/getsentry/sentry-cocoa.git
  3. Select version rule: "Up to Next Major" from
    9.5.0
SPM Products: Choose based on your needs:
ProductUse Case
Sentry
Default (static linking)
Sentry-Dynamic
Dynamic framework
SentrySwiftUI
SwiftUI view performance tracking
Sentry-WithoutUIKitOrAppKit
App extensions or CLI tools
  1. 点击 File > Add Package Dependencies
  2. 输入:
    https://github.com/getsentry/sentry-cocoa.git
  3. 选择版本规则:从
    9.5.0
    开始“Up to Next Major”(兼容下一个大版本)
SPM产品选择:根据需求选择:
产品使用场景
Sentry
默认选项(静态链接)
Sentry-Dynamic
动态框架
SentrySwiftUI
SwiftUI视图性能追踪
Sentry-WithoutUIKitOrAppKit
应用扩展或CLI工具

CocoaPods

CocoaPods

ruby
undefined
ruby
undefined

Podfile

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

配置选项

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
UIUIViewController loads, user interactions
File I/ORead/write operations
Core DataFetch/save operations
FramesSlow 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, fatal
swift
let logger = SentrySDK.logger

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

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

Session 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 = true
.
iOS 26+ / Xcode 26+ 注意事项:由于Apple的Liquid Glass渲染会破坏遮罩可靠性,使用Xcode 26.0+构建的SDK 8.57.0+会自动在iOS 26.0+上禁用会话重放。在iOS <26或Xcode <26环境下重放功能仍可正常使用。如需强制启用(请谨慎使用):
options.experimental.enableSessionReplayInUnreliableEnvironment = true

Masking

内容遮罩

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-sentry
bash
bundle exec fastlane add_plugin fastlane-plugin-sentry

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 the Sentry UI after the upload completes.
bash
bundle exec fastlane sentry_size
上传完成后,可在Sentry UI中查看分析结果。

Troubleshooting

故障排查

IssueSolution
Events not appearingCheck DSN, enable
debug = true
No tracesSet
tracesSampleRate
> 0
No replaysSet
sessionSampleRate
> 0, check SDK 8.31.1+. On iOS 26+/Xcode 26+ see Liquid Glass caveat above
No logsSet
enableLogs = true
(SDK 9.0.0+) or
experimental.enableLogs = true
(SDK 8.55.0-8.x)
CocoaPods failsRun
pod repo update
, check iOS 15+ target
Size upload failsCheck
SENTRY_AUTH_TOKEN
, verify org/project slugs
问题解决方案
事件未显示检查DSN是否正确,启用
debug = true
无追踪数据设置
tracesSampleRate
> 0
无重放内容设置
sessionSampleRate
> 0,检查SDK版本是否为8.31.1+。对于iOS 26+/Xcode 26+环境,请参考上述Liquid Glass相关注意事项
无日志数据SDK 9.0.0+版本设置
enableLogs = true
;SDK 8.55.0-8.x版本设置
experimental.enableLogs = true
CocoaPods安装失败运行
pod repo update
,检查目标平台是否为iOS 15+
包大小上传失败检查
SENTRY_AUTH_TOKEN
是否正确,验证组织/项目slug是否正确