一种可能的解决方法是请求网站的桌面模式,这将显示预期的内容而不是重定向您。
使用 UIWebView:
UserDefaults.standard.register(defaults: ["UserAgent": "Custom-Agent"])
确保在加载URLRequest 之前注册此自定义代理。请注意,此方法将适用于您的应用程序中的所有 UIWebView 对象。如果您只想加载一些特定视图来加载桌面版本,则需要使用WKWebView,如下所示,因为它允许您为每个对象使用自定义代理。
使用 WKWebView:
首先,您必须import WebKit。然后,像这样初始化它:
let url = URL(string: "https://itunes.apple.com/us/album/burn-that-broken-bed/id1120162623?i=1120163074&uo=4")!
let wkWebView = WKWebView(frame: self.view.frame, configuration: WKWebViewConfiguration())
wkWebView.uiDelegate = self // Optional line - must conform to WKUIDelegate
// the line below specifies the custom agent, which allows you to request the desktop version of the website
wkWebView.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"
wkWebView.load(URLRequest(url: url))
self.view.addSubview(wkWebView)
更新:(集成 WKWebView)
不幸的是,从 XCode 8 开始,您无法在 IB 中添加 WKWebView,因此您必须以编程方式添加它。这里的好消息是,您可以使用您在 IB 中创建的 UIWebView 的 frame 来稍微简化 WKWebView 对象的编程实例化
检查一下:(未经测试的代码)
// for ease of use
extension WKWebView {
func setDesktopMode(on: Bool) {
if on {
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"
return
}
customUserAgent = nil
}
}
在您的自定义单元格文件中
class MyCustomCell: UICollectionViewCell {
var wkWebView: WKWebView! // add this line
@IBOutlet weak var webView: UIWebView! // the one you created in IB
}
然后在你的 UIViewController 中
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellIdentifier", for: indexPath) as! MyCustomCell
let url = URL(string: "url here")!
cell.wkWebView = WKWebView(frame: cell.webView.frame, configuration: WKWebViewConfiguration()) // using the webView's frame that was created in IB
cell.wkWebView.uiDelegate = self // Optional line - must conform to WKUIDelegate
cell.wkWebView.setDesktopMode(on: true) // true = loads desktop mode (for your iTunes URLs)
cell.wkWebView.load(URLRequest(url: url))
return cell
}