Change User-Agent
Asked Answered
H

3

6

How can I change in my WebView the default string of User-Agent?

@IBOutlet weak var myWbView: UIWebView!
let myURL = NSURL(string: "http://http://web-example")
let myURLRequest:NSURLRequest = NSURLRequest(URL: myURL!)
myWbView.loadRequest(myURLRequest)
Hopehopeful answered 27/4, 2016 at 12:34 Comment(2)
When I Google e.g. WebView change useragent swift I seem to be getting a lot of results?Number
There are a lot of results and I don't understand what is the result for meHopehopeful
T
8

If you want to set User-Agent HTTP header for your request that is going to be used for Web-view loading,

let userAgent = "Custom User Agent";
let myURL = NSURL(string: "http://http://web-example")
let myURLRequest:NSURLRequest = NSMutableURLRequest(URL: myURL!)
myWbView.loadRequest(myURLRequest)    
myURLRequest.setValue(userAgent, forHTTPHeaderField: "User-Agent")

If you want to set User-Agent for all requests in your app, see this question How can I set the "User-Agent" header of a UIWebView in Swift

Thermobarometer answered 27/4, 2016 at 12:44 Comment(3)
@Alexander Tkachenko your code is not usable, but the link before was right for me, so thank youHopehopeful
It seems that UIWebView does not actually let you override the user agent in this way. https://mcmap.net/q/1772854/-user-agent-not-changing-in-nsmutableurlrequestEffulgent
Not useable! The custom user Agent is always be overridden with the default. You can test the "allHTTPHeaderFields" in UIWebViewDelegate-Method: shouldStartLoadWith after the "webView.loadRequest" call.Adapa
T
1

Actually, this is very easy. For that, you should use NSMutableURLRequest, initialize it with the NSURL, and set any user agent value using method setValue:ForHTTPHeaderField:, where field would be User-Agent, load it on the web view. That's it! Good luck!

Thorianite answered 27/4, 2016 at 12:44 Comment(0)
H
1

Swift 4.2

You always can override global UserAgent field, it is resolve your problem:

UserDefaults.standard.register(defaults: ["UserAgent" : "Custom UserAgent)"])
Hydrosphere answered 22/10, 2018 at 17:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.