-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSTCrashDetector.swift
More file actions
76 lines (66 loc) · 2.67 KB
/
STCrashDetector.swift
File metadata and controls
76 lines (66 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//
// STCrashDetector.swift
// STBaseProject
//
// Created by 寒江孤影 on 2024/01/01.
//
import Foundation
public final class STCrashDetector {
public static let shared = STCrashDetector()
private let crashKey = "STCrashDetector_app_crashed"
private let launchTimeKey = "STCrashDetector_app_launch_time"
private let backgroundTimeKey = "STCrashDetector_app_background_time"
public var onCrashDetected: (([String: Any]) -> Void)?
private init() {}
/// 标记应用已启动
public func markAppLaunch() {
UserDefaults.standard.set(true, forKey: self.crashKey)
UserDefaults.standard.set(Date().timeIntervalSince1970, forKey: self.launchTimeKey)
STLog("✅ 应用启动标记已设置")
}
/// 标记应用已正常终止
public func markAppTermination() {
UserDefaults.standard.set(false, forKey: self.crashKey)
STLog("✅ 应用正常终止标记已设置")
}
/// 标记应用进入后台
public func markAppBackgroundEntry() {
UserDefaults.standard.set(Date().timeIntervalSince1970, forKey: self.backgroundTimeKey)
STLog("✅ 应用后台标记已设置")
}
/// 检查是否有崩溃
/// - Returns: 如果有崩溃返回 true,否则返回 false
public func detectCrash() -> Bool {
let wasCrashed = UserDefaults.standard.bool(forKey: self.crashKey)
if wasCrashed {
STLog("⚠️ 检测到应用崩溃")
let crashInfo = self.crashInfo()
self.onCrashDetected?(crashInfo)
UserDefaults.standard.set(false, forKey: self.crashKey)
return true
}
return false
}
/// 获取崩溃信息
/// - Returns: 崩溃信息字典
public func crashInfo() -> [String: Any] {
let launchTime = UserDefaults.standard.double(forKey: self.launchTimeKey)
let backgroundTime = UserDefaults.standard.double(forKey: self.backgroundTimeKey)
var crashInfo: [String: Any] = [:]
if launchTime > 0 {
crashInfo["last_launch_time"] = Date(timeIntervalSince1970: launchTime)
crashInfo["time_since_launch"] = Date().timeIntervalSince1970 - launchTime
}
if backgroundTime > 0 {
crashInfo["last_background_time"] = Date(timeIntervalSince1970: backgroundTime)
}
return crashInfo
}
/// 清除所有崩溃检测数据
public func clearCrashData() {
UserDefaults.standard.removeObject(forKey: self.crashKey)
UserDefaults.standard.removeObject(forKey: self.launchTimeKey)
UserDefaults.standard.removeObject(forKey: self.backgroundTimeKey)
STLog("🧹 崩溃检测数据已清除")
}
}