Change User-Agent

旧巷老猫 提交于 2019-11-28 06:26:42

问题


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)

回答1:


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




回答2:


Swift 4.2

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

UserDefaults.standard.register(defaults: ["UserAgent" : "Custom UserAgent)"])



回答3:


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!



来源:https://stackoverflow.com/questions/36889970/change-user-agent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!