我想在iOS设备中获得桌面版本的URL响应。但我总是得到移动版本的URL响应。下面是我的代码:
var request = URLRequest(url: URL(string: "https://www.youtube.com")!)
request.addValue("Chrome Safari", forHTTPHeaderField: "User-Agent")
let session = URLSession.init(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: request) { (data, response, error) in
if let data = data, let str = String(data: data, encoding: .utf8) {
print(str)
}
}
task.resume()
该代码将获得移动版本响应。如何获得桌面版URL响应?
我想获得桌面响应的og
信息,而不是使用WKWebView
来呈现网站。
可能重复:
如何在Swift 3.0中使用UIWebView请求网页的桌面版本?
答:
你可以使用WKWebViewcustomUserAgent
属性来获得一个桌面版的网页:
https://developer.apple.com/documentation/webkit/wkwebview/1414950-customuseragent
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"
当然,您需要修改web浏览器版本以获得实际响应:
Mozilla Firefox: https://www.mozilla.org/en-US/firefox/releases/
谷歌Chrome: https://www.whatismybrowser.com/guides/the-latest-version/chrome
苹果Safari: https://developer.apple.com/documentation/safari-release-notes
https://www.whatismybrowser.com/guides/the-latest-version/safari