5

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)
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Phocs
  • 2,430
  • 5
  • 18
  • 35

3 Answers3

6

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

Community
  • 1
  • 1
Alexander Tkachenko
  • 3,221
  • 1
  • 33
  • 47
  • @Alexander Tkachenko your code is not usable, but the link before was right for me, so thank you – Phocs Apr 27 '16 at 22:47
  • 2
    It seems that UIWebView does not actually let you override the user agent in this way. http://stackoverflow.com/a/20632315/1148843 – Chad Jan 31 '17 at 21:36
  • 1
    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. – Peter Kreinz Aug 31 '17 at 15:21
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!

Fahri Azimov
  • 11,470
  • 2
  • 21
  • 29
1

Swift 4.2

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

UserDefaults.standard.register(defaults: ["UserAgent" : "Custom UserAgent)"])
akonoplev
  • 79
  • 5