UserAgent.swift
1.98 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
//
// UserAgent.swift
// hippo
//
// Created by shihao on 2025/7/10.
//
import Foundation
import UIKit
import WebKit
extension UIApplication {
var currentWindowScene: UIWindowScene? {
connectedScenes
.compactMap { $0 as? UIWindowScene }
.first { $0.activationState != .unattached }
}
var currentScreen: UIScreen? {
currentWindowScene?.screen
}
}
class UserAgent {
var unifiedUA: String = ""
var finalUA: String = ""
private(set) var appVersion: String?
private(set) var buildVersion: String?
private(set) var deviceInfo: String?
func genUA(){
let web = WKWebView()
if let ua = web.value(forKey: "userAgent") as? String {
self.unifiedUA = ua
}
self.finalUA = self.unifiedUA + self.customUA()
}
func customUA() -> String {
let version = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey) as! NSString
let bundle = Bundle.main.infoDictionary?["CFBundleShortVersionString"] ?? ""
let hardware = Self.hardwareString()
deviceInfo = hardware
AppGroupConstants.defaults?.set(hardware, forKey: AppGroupConstants.Key.deviceInfo)
let systemVersion = UIDevice.current.systemVersion
let height = UIApplication.shared.currentScreen?.bounds.height ?? 0
let width = UIApplication.shared.currentScreen?.bounds.width ?? 0
let ua = " doublefeel/\(version)(\(bundle))(\(hardware); iOS \(systemVersion); \(height)x\(width))"
appVersion = bundle as? String
buildVersion = version as String
return ua
}
private static func hardwareString() -> String {
var systemInfo = utsname()
uname(&systemInfo)
return withUnsafePointer(to: &systemInfo.machine) { pointer in
pointer.withMemoryRebound(to: CChar.self, capacity: 1) { machine in
String(cString: machine)
}
}
}
}