How do I change the user agent in my WebView using Swift 4.2?

旧巷老猫 提交于 2021-02-16 09:36:46

问题


I'm struggling with changing the user agent on my project using the latest Xcode version with swift 4.2 .

I want to pretend that I'm a Mac visiting a specific website. Please edit this code and post it in the comments

Here's my code so far.

class ViewController: UIViewController {
    @IBOutlet weak var webview: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let userAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36 Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10"
        let myURL = NSURL(string: "http://website.com")
        let myURLRequest:NSURLRequest = URLRequest(url: myURL! as URL) as NSURLRequest
        webview.load(myURLRequest as URLRequest)
        myURLRequest.setValue(userAgent, forKey: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36")

        webview.load(URLRequest(url: myURL! as URL))
    }
}

If I build it I receive this error:

![Error][2].


回答1:


The problem i seeing here, first time loading without the user-agent set and then setting it wrongly and put another request

Please check the appledoc, for setting up the HTTPHeaderField.

Based on your given code, the solution would be

class ViewController: UIViewController {
     @IBOutlet weak var webview: WKWebView!

     override func viewDidLoad() {
        super.viewDidLoad()

        let userAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36 Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10"
        if let myURL = URL(string: "http://website.com") {
            var myURLRequest= URLRequest(url: myURL)
            myURLRequest.setValue(userAgent, forHTTPHeaderField:"user-agent")
            webview.load(myURLRequest)
        }

    }
}



回答2:


WKWebView has a property called customUserAgent exactly for this purpose:

let customUserAgent = "Mozilla/5.0 ..." // Your custom user agent string goes here"
webView.customUserAgent = customUserAgent


来源:https://stackoverflow.com/questions/53352822/how-do-i-change-the-user-agent-in-my-webview-using-swift-4-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!