Load desktop version WKWebView iOS 9

牧云@^-^@ 提交于 2019-12-19 11:45:06

问题


Up until recently

let url = NSURL (string:http://asite.com)        
let request = NSMutableURLRequest(URL: url!)         

//iOS loads the mobile version of asite.com which does not have the required DOM so we force the desktop version by setting new value forHTTPHeadrField
let newUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.6 Safari/537.11"

request.setValue(newUserAgent, forHTTPHeaderField: "User_Agent")

let config = WKWebViewConfiguration()        

//even though we dont need to see it the webpage needs to appear but we set its frame to CGRectZero so its hidden from user 

let ghostWebView : WKWebView = WKWebView(frame:CGRectZero, configuration: config)        
ghostWebView.loadRequest(request)

This would force the desktop version of the site. However it has just stopped working. Not sure exactly when but very recently.

Any ideas why?

Also google results show some use

"User-Agent"

for the HTTPHeaderField and others

"User_Agent"

whats the difference between the two?

Update: I solved the issue by changing the User Agent string to

"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"

Which I got from

http://www.useragentstring.com

So my new question is how often do these user agent strings change and is there a way for my app to auto update to the newest one?


回答1:


Swift 4:

@IBOutlet weak var webView: WKWebView!

override func viewDidLoad() {
      super.viewDidLoad()
      self.webView.customUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/601.6.17 (KHTML, like Gecko) Version/9.1.1 Safari/601.6.17"
}



回答2:


One way to resolve this it's by setting applicationNameForUserAgent property of WKWebViewConfiguration.

The default value is "Mobile/13C75", but you can set it with "Chrome/23.0.1271.6 Safari/537.11" or just "Chrome Safari" and you will get the desktop version of the requested URL.

WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];    
wkWebConfig.applicationNameForUserAgent = @"Chrome Safari";    
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero
                                        configuration:wkWebConfig];



回答3:


To help any who find themselves here for an answer. The solution was

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


来源:https://stackoverflow.com/questions/33434153/load-desktop-version-wkwebview-ios-9

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