-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSTDeviceInfo.swift
More file actions
628 lines (509 loc) · 15.8 KB
/
STDeviceInfo.swift
File metadata and controls
628 lines (509 loc) · 15.8 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//
// STDeviceInfo.swift
// STBaseProject
//
// Created by 寒江孤影 on 2019/02/10.
//
import UIKit
import Darwin
import Network
import SystemConfiguration
public struct STDeviceInfo {
public struct STAppInfo: Sendable {
public let version: String
public let buildVersion: String
public let bundleIdentifier: String
public let displayName: String
}
public struct STBatteryInfo: Sendable {
public let level: Float
public let percentage: Int
public let state: STBatteryState
public var isCharging: Bool {
state == .charging
}
public var isFull: Bool {
state == .full
}
fileprivate var legacyDictionary: [String: Any] {
[
"battery_level": level,
"battery_percentage": percentage,
"battery_state": state.rawValue,
"is_charging": isCharging,
"is_full": isFull
]
}
}
public struct STStorageInfo: Sendable {
public let total: Int64
public let free: Int64
public var used: Int64 {
max(total - free, 0)
}
public var usagePercentage: Double {
total > 0 ? Double(used) / Double(total) * 100.0 : 0.0
}
}
public struct STMemoryInfo: Sendable {
public let total: Int64
public let free: Int64
public var used: Int64 {
max(total - free, 0)
}
public var usagePercentage: Double {
total > 0 ? Double(used) / Double(total) * 100.0 : 0.0
}
}
}
// MARK: - App Information
public extension STDeviceInfo {
static var appInfoDictionary: [String: Any] {
Bundle.main.infoDictionary ?? [:]
}
static var appInfo: STAppInfo {
STAppInfo(
version: bundleString(for: "CFBundleShortVersionString"),
buildVersion: bundleString(for: "CFBundleVersion"),
bundleIdentifier: Bundle.main.bundleIdentifier ?? "",
displayName: bundleString(for: "CFBundleDisplayName", fallbackKey: "CFBundleName")
)
}
static var appVersion: String {
appInfo.version
}
static var appName: String {
appInfo.displayName
}
static var appBuildVersion: String {
appInfo.buildVersion
}
static var appBundleIdentifier: String {
appInfo.bundleIdentifier
}
}
// MARK: - Screen & Orientation
public extension STDeviceInfo {
@MainActor
static var interfaceOrientation: UIInterfaceOrientation {
preferredWindowScene()?.interfaceOrientation ?? .unknown
}
@MainActor
static var isLandscape: Bool {
interfaceOrientation.isLandscape
}
@MainActor
static var isPortrait: Bool {
interfaceOrientation.isPortrait
}
@MainActor
static var screenBounds: CGRect {
UIScreen.main.bounds
}
@MainActor
static var screenSize: CGSize {
screenBounds.size
}
@MainActor
static var screenScale: CGFloat {
UIScreen.main.scale
}
/// 屏幕宽度
@MainActor
static var screenWidth: CGFloat {
screenBounds.width
}
/// 屏幕高度
@MainActor
static var screenHeight: CGFloat {
screenBounds.height
}
/// 顶部 / 底部安全区(基于当前 key window)
@MainActor
static var safeAreaInsets: UIEdgeInsets {
preferredWindowScene()?.windows.first(where: \.isKeyWindow)?.safeAreaInsets ?? .zero
}
@MainActor
static var topSafeAreaHeight: CGFloat {
safeAreaInsets.top
}
@MainActor
static var bottomSafeAreaHeight: CGFloat {
safeAreaInsets.bottom
}
/// 是否是带刘海设备(通过顶部安全区高度粗略判断)
@MainActor
static var hasNotch: Bool {
topSafeAreaHeight > 20
}
/// 状态栏高度
@MainActor
static var statusBarHeight: CGFloat {
preferredWindowScene()?.statusBarManager?.statusBarFrame.height ?? 0
}
/// 默认导航栏高度
static let navigationBarHeight: CGFloat = 44.0
/// 默认标签栏高度
static let tabBarHeight: CGFloat = 49.0
}
// MARK: - Device Information
public extension STDeviceInfo {
static var systemVersion: String {
UIDevice.current.systemVersion
}
/// iOS 主版本号(如 18.2 -> 18)
static var systemMajorVersion: Int {
Int(systemVersion.split(separator: ".").first ?? "0") ?? 0
}
static var systemName: String {
UIDevice.current.systemName
}
static var deviceName: String {
UIDevice.current.name
}
static var deviceModelName: String {
UIDevice.current.model
}
static var deviceIdentifier: String {
currentDeviceIdentifier()
}
static var deviceType: STDeviceType {
deviceType(for: deviceIdentifier)
}
/// 是否运行在 iPhone 设备
static var isIPhone: Bool {
deviceType == .iPhone
}
/// 是否运行在 iPad 设备
static var isIPad: Bool {
deviceType == .iPad
}
static var devicePerformanceLevel: STDevicePerformanceLevel {
performanceLevel(totalRAM: totalRAM, cpuCoreCount: ProcessInfo.processInfo.activeProcessorCount)
}
}
// MARK: - Battery & Runtime
public extension STDeviceInfo {
static var batteryInfo: STBatteryInfo {
withBatteryMonitoring(makeBatteryInfo)
}
static var batteryLevel: Int {
batteryInfo.percentage
}
static var isCharging: Bool {
batteryInfo.isCharging
}
static var isRunningOnSimulator: Bool {
#if targetEnvironment(simulator)
true
#else
false
#endif
}
static var isDeviceJailbroken: Bool {
guard !isRunningOnSimulator else {
return false
}
for path in jailbreakPaths where FileManager.default.fileExists(atPath: path) {
return true
}
return canWriteToRestrictedPath()
}
/// 兼容旧安全检测 API:检测越狱环境
static func st_detectJailbreak() -> Bool {
isDeviceJailbroken
}
/// 兼容旧安全检测 API:检测模拟器环境
static func st_detectSimulator() -> Bool {
isRunningOnSimulator
}
/// 检测网络是否可达
static func st_detectNetworkConnection() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
guard let defaultRouteReachability else {
return false
}
var flags = SCNetworkReachabilityFlags()
guard SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) else {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return isReachable && !needsConnection
}
static var isLowPowerModeEnabled: Bool {
ProcessInfo.processInfo.isLowPowerModeEnabled
}
static var thermalState: STThermalState {
STThermalState(ProcessInfo.processInfo.thermalState)
}
}
// MARK: - Storage
public extension STDeviceInfo {
static var storageInfo: STStorageInfo {
let attributes = fileSystemAttributes()
let total = attributes[.systemSize] as? Int64 ?? 0
let free = attributes[.systemFreeSize] as? Int64 ?? 0
return STStorageInfo(total: total, free: free)
}
static var totalStorage: Int64 {
storageInfo.total
}
static var freeStorage: Int64 {
storageInfo.free
}
static var usedStorage: Int64 {
storageInfo.used
}
static var storageUsagePercentage: Double {
storageInfo.usagePercentage
}
}
// MARK: - Memory
public extension STDeviceInfo {
static var totalRAM: Int64 {
Int64(ProcessInfo.processInfo.physicalMemory)
}
static var memoryInfo: STMemoryInfo {
STMemoryInfo(total: totalRAM, free: freeMemoryBytes())
}
static var freeRAM: Int64 {
memoryInfo.free
}
static var usedRAM: Int64 {
memoryInfo.used
}
static var memoryUsagePercentage: Double {
memoryInfo.usagePercentage
}
}
// MARK: - Network
public extension STDeviceInfo {
static func currentNetworkConnectionType(completion: @escaping @Sendable (STNetworkConnectionType) -> Void) {
let monitor = NWPathMonitor()
let queue = DispatchQueue(label: "com.stbaseproject.deviceinfo.network")
monitor.pathUpdateHandler = { path in
completion(connectionType(for: path))
monitor.cancel()
}
monitor.start(queue: queue)
}
static func currentNetworkConnectionType() async -> STNetworkConnectionType {
await withCheckedContinuation { continuation in
currentNetworkConnectionType { connectionType in
continuation.resume(returning: connectionType)
}
}
}
}
// MARK: - Private Helpers
private extension STDeviceInfo {
static let jailbreakPaths = [
"/Applications/Cydia.app",
"/Library/MobileSubstrate/MobileSubstrate.dylib",
"/bin/bash",
"/usr/sbin/sshd",
"/etc/apt",
"/private/var/lib/apt/",
"/private/var/lib/cydia",
"/private/var/mobile/Library/SBSettings/Themes"
]
static func bundleString(for key: String, fallbackKey: String? = nil) -> String {
if let value = Bundle.main.object(forInfoDictionaryKey: key) as? String, !value.isEmpty {
return value
}
guard let fallbackKey, let value = Bundle.main.object(forInfoDictionaryKey: fallbackKey) as? String else {
return ""
}
return value
}
static func preferredWindowScene() -> UIWindowScene? {
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
if let activeScene = scenes.first(where: {
$0.activationState == .foregroundActive && $0.windows.contains(where: \.isKeyWindow)
}) {
return activeScene
}
if let foregroundScene = scenes.first(where: { $0.activationState == .foregroundActive }) {
return foregroundScene
}
return scenes.first
}
static func withBatteryMonitoring<T>(_ operation: (UIDevice) -> T) -> T {
let device = UIDevice.current
let previousValue = device.isBatteryMonitoringEnabled
if !previousValue {
device.isBatteryMonitoringEnabled = true
}
defer {
if !previousValue {
device.isBatteryMonitoringEnabled = false
}
}
return operation(device)
}
static func currentDeviceIdentifier() -> String {
var systemInfo = utsname()
uname(&systemInfo)
return withUnsafePointer(to: &systemInfo.machine) { pointer in
pointer.withMemoryRebound(to: CChar.self, capacity: 1) {
String(cString: $0)
}
}
}
static func deviceType(for identifier: String) -> STDeviceType {
if identifier.hasPrefix("iPhone") {
return .iPhone
}
if identifier.hasPrefix("iPad") {
return .iPad
}
if identifier.hasPrefix("iPod") {
return .iPod
}
if identifier.hasPrefix("AppleTV") {
return .appleTV
}
if identifier.hasPrefix("Watch") {
return .appleWatch
}
if identifier.hasPrefix("Mac") {
return .mac
}
return .unknown
}
static func performanceLevel(totalRAM: Int64, cpuCoreCount: Int) -> STDevicePerformanceLevel {
let totalRAMInGB = Double(totalRAM) / 1_073_741_824.0
if totalRAMInGB >= 6.0 || cpuCoreCount >= 6 {
return .high
}
if totalRAMInGB >= 3.0 || cpuCoreCount >= 4 {
return .medium
}
return .low
}
static func makeBatteryInfo(for device: UIDevice) -> STBatteryInfo {
let batteryState = STBatteryState(device.batteryState)
let batteryLevel = device.batteryLevel
let percentage = batteryLevel >= 0 ? Int((batteryLevel * 100.0).rounded()) : -1
return STBatteryInfo(
level: batteryLevel,
percentage: percentage,
state: batteryState
)
}
static func canWriteToRestrictedPath() -> Bool {
let testPath = "/private/jailbreak_test"
do {
try "test".write(toFile: testPath, atomically: true, encoding: .utf8)
try FileManager.default.removeItem(atPath: testPath)
return true
} catch {
return false
}
}
static func fileSystemAttributes() -> [FileAttributeKey: Any] {
do {
return try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory())
} catch {
STLog("[STDeviceInfo] 读取文件系统属性失败: \(error.localizedDescription)", level: .warning)
return [:]
}
}
static func freeMemoryBytes() -> Int64 {
var vmStats = vm_statistics64()
var size = mach_msg_type_number_t(MemoryLayout.size(ofValue: vmStats) / MemoryLayout<integer_t>.size)
let hostPort = mach_host_self()
let result = withUnsafeMutablePointer(to: &vmStats) {
$0.withMemoryRebound(to: integer_t.self, capacity: Int(size)) {
host_statistics64(hostPort, HOST_VM_INFO64, $0, &size)
}
}
guard result == KERN_SUCCESS else {
return 0
}
let freeMemory = UInt64(vmStats.free_count) * UInt64(vm_page_size)
return Int64(freeMemory)
}
static func connectionType(for path: NWPath) -> STNetworkConnectionType {
if path.usesInterfaceType(.wifi) {
return .wifi
}
if path.usesInterfaceType(.cellular) {
return .cellular
}
if path.usesInterfaceType(.wiredEthernet) {
return .ethernet
}
return .unknown
}
}
// MARK: - Enums
public enum STBatteryState: String, Sendable {
case charging
case full
case unplugged
case unknown
fileprivate init(_ state: UIDevice.BatteryState) {
switch state {
case .charging:
self = .charging
case .full:
self = .full
case .unplugged:
self = .unplugged
case .unknown:
self = .unknown
@unknown default:
self = .unknown
}
}
}
public enum STDeviceType: String, Sendable {
case iPhone = "iphone"
case iPad = "ipad"
case iPod = "ipod"
case appleTV = "apple_tv"
case appleWatch = "apple_watch"
case mac = "mac"
case unknown = "unknown"
}
public enum STNetworkConnectionType: String, Sendable {
case wifi = "wifi"
case cellular = "cellular"
case ethernet = "ethernet"
case unknown = "unknown"
}
public enum STDevicePerformanceLevel: String, Sendable {
case low = "low"
case medium = "medium"
case high = "high"
}
public enum STThermalState: String, Sendable {
case nominal = "nominal"
case fair = "fair"
case serious = "serious"
case critical = "critical"
case unknown = "unknown"
fileprivate init(_ state: ProcessInfo.ThermalState) {
switch state {
case .nominal:
self = .nominal
case .fair:
self = .fair
case .serious:
self = .serious
case .critical:
self = .critical
@unknown default:
self = .unknown
}
}
}