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