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].
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With