UserAgent.swift 1.55 KB
//
//  UserAgent.swift
//  hippo
//
//  Created by shihao on 2025/7/10.
//

import Foundation
import WebKit
import DeviceGuru

extension UIApplication {
    var currentWindowScene: UIWindowScene? {
        connectedScenes
            .compactMap { $0 as? UIWindowScene }
            .first { $0.activationState != .unattached }
    }

    var currentScreen: UIScreen? {
        currentWindowScene?.screen
    }
}

class UserAgent {
    static let share = UserAgent()
    var unifiedUA: String = ""
    var finalUA: String = ""
    
    private(set) var appVersion: String?
    private(set) var buildVersion: 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 = DeviceGuruImplementation().hardwareString
        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
    }
    
}