WKWebView将谷歌搜索结果显示为原始html

时间:2016-02-17 03:55:59

标签: ios swift uiwebview wkwebview wkwebviewconfiguration

我正在尝试在我正在使用iOS WKWebView的应用程序中添加Web浏览器。

但WKWebView加载谷歌搜索结果的原始html。 https://i.imgur.com/LJemP75.jpg

以下是我正在使用的代码的一部分:

let configuration = WKWebViewConfiguration()
configuration.allowsInlineMediaPlayback = true

webView = WKWebView(frame: CGRect.zero, configuration: configuration)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)
webView.navigationDelegate = self
webView.UIDelegate = self
webviewHolder.addSubview(webView)

webView.scrollView.backgroundColor = UIColor.clearColor()
webView.backgroundColor = UIColor.clearColor()
webView.opaque = false
webView.clipsToBounds = false
webView.scrollView.clipsToBounds = false

以及WKNavigationDelegate和WKUIDelegate实施:

//MARK: WKNavigationDelegate
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
    pageLoaded = true
    updateBarButtons()
    addressBarTextField.text = webView.URL?.absoluteString
    UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}

func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
    cantConnectView.hidden = false
    webView.hidden = true
}

func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
    cantConnectView.hidden = false
    webView.hidden = true
    UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}

func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    updateBarButtons()
    addressBarTextField.text = webView.URL?.absoluteString
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}

func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
    decisionHandler(.Allow)
}

func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) {
    decisionHandler(.Allow)
}

//MARK: WKUIDelegate
func webView(webView: WKWebView, createWebViewWithConfiguration configuration: WKWebViewConfiguration, forNavigationAction navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    if navigationAction.targetFrame == nil {
        webView.loadRequest(navigationAction.request)
    }

    return nil
}

任何让WKWebView正确加载谷歌搜索的想法?

1 个答案:

答案 0 :(得分:1)

使用Safari的用户代理

修复了此问题
if #available(iOS 9.0, *) {
    webView.customUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13D15 Safari/601.1"
}