问题
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