如何在不使用不推荐使用的WebView的情况下使用swift获取用户代理 [英] How to get user agent using swift without using the deprecated WebView
本文介绍了如何在不使用不推荐使用的WebView的情况下使用swift获取用户代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要获取用户代理.我曾经使用UIWebView来获取它,但现在不推荐使用.
I need to get the user agent. I used to get it using UIWebView but it's deprecated now.
let userAgent = UIWebView().stringByEvaluatingJavaScript(from: "navigator.userAgent")!
推荐答案
我们可以使用下面的代码片段
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")
}
})
}
}
输出:userAgent:Mozilla/5.0(iPhone; CPU iPhone OS 13_3,如MacOS X)AppleWebKit/605.1.15(KHTML,例如Gecko)Mobile/15E148
Output : userAgent: Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
这篇关于如何在不使用不推荐使用的WebView的情况下使用swift获取用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文