我正在尝试在我的应用上添加移动,桌面版网站功能.但问题是用户代理只在webView加载之前立即更改.在我的应用程序中,我添加了一个用于移动的按钮,第二个用于桌面版本站点UIWebView刚刚
var defaultUserAgent = String() @IBOutlet weak var webView: UIWebView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() let url = NSURL(string: "https://www.youtube.com") let request = NSURLRequest(URL: url!) activityIndicator.hidesWhenStopped = true activityIndicator.startAnimating() webView.loadRequest(request) } @IBAction func mobile(sender: AnyObject) { NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": defaultUserAgent]) print(defaultUserAgent) let url = NSURL(string: "https://www.youtube.com") let request = NSURLRequest(URL: url!) activityIndicator.hidesWhenStopped = true activityIndicator.startAnimating() webView.loadRequest(request) } @IBAction func desktop(sender: AnyObject) { NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36"]) let url = NSURL(string: "https://www.youtube.com") let request = NSURLRequest(URL: url!) activityIndicator.hidesWhenStopped = true activityIndicator.startAnimating() webView.loadRequest(request) } func webViewDidFinishLoad(webView: UIWebView) { activityIndicator.stopAnimating() print(webView.stringByEvaluatingJavaScriptFromString("navigator.userAgent")) defaultUserAgent = webView.stringByEvaluatingJavaScriptFromString("navigator.userAgent")! }我建议您使用 WkWebView而不是UIWebView,因为它相对更强大
iOS 9的WkWebView有一个直接的API
if #available(iOS 9, *) { webViewObj.customUserAgent = "customUserAgentValue" }