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
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
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