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

后端 未结 2 835
深忆病人
深忆病人 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

    0 讨论(0)
  • 2021-01-29 01:57

    Use WebKit instead.

    import WebKit
    
    let webView = WKWebView()
    webView.evaluateJavaScript("navigator.userAgent") { (result, error) in
        print(result as! String)
    }
    
    // Output 
    Mozilla/5.0 (iPad; CPU OS 13_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
    
    0 讨论(0)
提交回复
热议问题