How to request desktop site in Swift programmatically (without UIWebView)?

若如初见. 提交于 2019-12-25 01:54:05

问题


Desktop site's HTML code has a link of "apple-touch-icon" thumbnail image in header, whereas mobile's one hasn't. I just need to fetch this html and parse.

So, how to request desktop site (maybe via URLRequest, URLSession or something else)?

p.s. I found, that I have to change User-Agent string value, but again, I didn't find, how to do this in Swift.


回答1:


Depends on server logic, but in most cases it's enough to set up userAgent Header in you request:

let url = URL(string:"https://google.com")!
var request = URLRequest(url: url)
let userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/605.1.12 (KHTML, like Gecko) Version/11.1 Safari/605.1.12"
request.addValue(userAgent, forHTTPHeaderField: "User-Agent")

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
 // Process reponse
}
task.resume()



回答2:


A WKWebView should solve your problem - you can define it in your code. Do this:

var webView : WKWebView!
override func loadView() {
    super.loadView()

    let config = WKWebViewConfiguration()
    webView = WKWebView(frame: self.view.frame, configuration: config)
    self.webView!.uiDelegate = self
    webView.customUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36"
    //load URL here
    let url = NSURL(string: "https://stackoverflow.com/")!
    webView.load(URLRequest(url: url as URL))
    self.view.addSubview(webView)


}


来源:https://stackoverflow.com/questions/48155315/how-to-request-desktop-site-in-swift-programmatically-without-uiwebview

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