I'm trying to add mobile, desktop version site functionality on my app. But the problem is that User Agent
only change at once before webView loading. In my app i add to button one for Mobile
and second for Desktop
version site. UIWebView
pick User Agent
just on start.Can anyone tell me is there any way to change User Agent
at run time. Thanks
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")!
}
Yes, the user-agent string can change. Session cookies often last longer than an individual browser session.
User-agent spoofing is a form of fraud where the string of data is modified to provide false information or hide details – for example, a bot making multiple automated requests for content from a single device could modify the user agent string to pretend those requests (and the resulting impressions) are from multiple ...
To change the user Agent, we shall take the help of ChromeOptions class. Then apply the add_argument method on the object created. We shall pass user-agent and <value of the user Agent> as parameters to that method. Finally, this information shall be passed to the driver object.
I recommend you to use WkWebView instead of UIWebView as it is comparatively more powerfull
WkWebView of iOS 9 has a direct API
if #available(iOS 9, *) {
webViewObj.customUserAgent = "customUserAgentValue"
}
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