Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.0k views
in Technique[技术] by (71.8m points)

swift - Load desktop version WKWebView iOS 9

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...