How to get the user agent on iOS?

后端 未结 6 2030
天涯浪人
天涯浪人 2020-12-14 19:59

Is there a way on iOS to get the user agent of the device? I don\'t want to hard code it since I need the user agent for all devices and I need to append the user agent to a

6条回答
  •  被撕碎了的回忆
    2020-12-14 20:29

    Swift 3.x, 4.x, 5.x, & above

    As sometime traditional UIWebView get's memory leaked so instead use always WKWebView (far better from UIWebView)

    import WebKit
    
    var webViewForUserAgent: WKWebView?
    

    and get userAgent by calling below function & you can also set it to your other variable

    func getUserAgent() {
    
        webViewForUserAgent = WKWebView() // must initialize
    
        webViewForUserAgent?.evaluateJavaScript("navigator.userAgent") { (result, error) in
    
            //
            if error != nil {
                print("Error occured to get userAgent")
                return
            }
    
            //
            if let unwrappedUserAgent = result as? String {
                print("userAgent: \(unwrappedUserAgent)")
            } else {
                print("Failed to get userAgent")
            }
        }
    }
    

提交回复
热议问题