我尝试了几乎所有的Stackoverflow和其他站点的所有请求,以请求WKWebview中的桌面版本的站点,但是没有一种解决方案对我有用。
我尝试过的链接如下
https://stackoverflow.com/a/38228810/3145189
https://stackoverflow.com/a/38228810/3145189
https://stackoverflow.com/a/49646773/3145189
https://stackoverflow.com/a/48155481/3145189
我尝试通过在上面的线程中评论答案来获得答案,但是没有得到答复,所以我在这里回答我的问题,希望您不要将其标记为重复
这是我尝试过的许多实现之一
import UIKit
import WebKit
class ViewController: UIViewController {
var webview: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let config = WKWebViewConfiguration()
webview = WKWebView(frame: self.view.frame, configuration: config)
self.webview.uiDelegate = self
let url = URL(string: "https://quora.com/")!
var request = URLRequest(url: url)
let 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"
request.addValue(userAgent, forHTTPHeaderField: "User-Agent")
webview.load(request)
//webview.customUserAgent = "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"
self.view.addSubview(webview)
}
}
extension ViewController: WKUIDelegate {
}
我会要求,因为我尝试了很多其他事情,所以请在发布答案之前对您的回答或建议进行测试。
编辑-
上面的示例代码运行正常,问题是更改用户代理不会立即反映出来,重新安装时用户代理的变化确实反映出来了,所以我的问题是如何使用按钮切换请求桌面站点。
答案 0 :(得分:1)
这是我经过测试的代码:
class ViewController: UIViewController {
var webview: WKWebView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
createWebView()
if let url = URL(string: "https://quora.com") {
load(url: url)
}
}
private func createWebView() {
let config = WKWebViewConfiguration()
let webview = WKWebView(frame: self.view.frame, configuration: config)
webview.uiDelegate = self
webview.navigationDelegate = self
self.webview = webview
self.view.addSubview(webview)
}
private func load(url: URL) {
var request = URLRequest(url: url)
let 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"
request.addValue(userAgent, forHTTPHeaderField: "User-Agent")
webview?.load(request)
}
}
extension ViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("\(#function)")
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("\(#function): \(error)")
}
}
extension ViewController: WKUIDelegate {
}
干杯!