How to get user agent using swift without using the deprecated WebView

后端 未结 2 834
深忆病人
深忆病人 2021-01-29 01:22

I need to get the user agent. I used to get it using UIWebView but it\'s deprecated now.

let userAgent = UIWebView().stringByEvaluatingJavaScript(from: \"naviga         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-29 01:34

    We can get the userAgent using below snippet of code,

    import UIKit
    import WebKit
    
    
    class ViewController: UIViewController{
    
        var WKwebView: WKWebView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
                getUserAgent()
        }
    
        func getUserAgent() {
    
                  let webConfiguration = WKWebViewConfiguration()
           WKwebView = WKWebView(frame: .zero, configuration: webConfiguration)
                 WKwebView.evaluateJavaScript("navigator.userAgent", completionHandler: { (result, error) in
                      debugPrint(result as Any)
                      debugPrint(error as Any)
    
                      if let unwrappedUserAgent = result as? String {
                          print("userAgent: \(unwrappedUserAgent)")
                      } else {
                          print("failed to get the user agent")
                      }
                  })
        }
    
    }
    

    Output : userAgent: Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148

提交回复
热议问题