PlatformHostApiImpl.swift
2.07 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
import Foundation
import UIKit
import WebKit
/**
* PlatformApi iOS implementation.
*
* 组装完整 User-Agent,格式与 Android 端保持一致:
* `{systemWebViewUA} doublefeel/{versionCode}({versionName})(Apple##Apple##{model}; iOS{osVersion}; {height}x{width})(huawei)`
*/
final class PlatformHostApiImpl: PlatformHostApi {
// WKWebView 必须在主线程创建,且需保持引用防止释放
private static let webView: WKWebView = {
let wv = WKWebView(frame: .zero)
return wv
}()
func getFullUserAgent() throws -> String {
// 1. 系统 WebView UA(同步读取,WKWebView 已在主线程初始化)
let systemUa = PlatformHostApiImpl.webView.value(forKey: "userAgent") as? String ?? ""
// 2. 版本信息(对应 Android versionCode / versionName)
let info = Bundle.main.infoDictionary
let versionName = info?["CFBundleShortVersionString"] as? String ?? ""
let versionCode = info?["CFBundleVersion"] as? String ?? "0"
// 3. 设备信息
// iOS 无 manufacturer/brand 概念,统一用 "Apple"
let manufacturer = "Apple"
let brand = "Apple"
let model = UIDevice.current.model // "iPhone" / "iPad"
let osVersion = UIDevice.current.systemVersion.replacingOccurrences(of: ".", with: "")
// 4. 屏幕物理分辨率:长边为 height,短边为 width
let bounds = UIScreen.main.bounds
let scale = UIScreen.main.scale
let pw = bounds.width * scale
let ph = bounds.height * scale
let screenWidth = Int(min(pw, ph))
let screenHeight = Int(max(pw, ph))
// 5. 组装 customAgent(与 Android DeviceInfoUtils.userAgent 格式一致)
let customAgent = "doublefeel/\(versionCode)(\(versionName))"
+ "(\(manufacturer)##\(brand)##\(model); iOS\(osVersion); \(screenHeight)x\(screenWidth))"
+ "(apple)"
let full = "\(systemUa.trimmingCharacters(in: .whitespaces)) \(customAgent)"
.trimmingCharacters(in: .whitespaces)
return full
}
}