使用Swift 4捕获WKWebView的HTTP错误代码

23

这个问题与以下内容相同:WKWebView捕获HTTP错误代码。不幸的是,Obj-C中的方法不适用于Swift 4,因此引用的WKNavigationResponse.response不再是类型为NSHTTPURLResponse,因此它没有HTTP状态码。

但问题仍然存在:我需要获取答案的HTTP状态码,以检测是否加载了期望的页面。

请注意,webView(_ webView:WKWebView,didFailProvisionalNavigation navigation:WKNavigation!,withError error:Error)委托在404的情况下不会被调用,而只有在网络问题(即服务器离线)的情况下才会被调用; 相反,将调用func webView(_ webView:WKWebView,didFinish navigation:WKNavigation!)

感谢您的回答。

2个回答

47

通过在WKWebView上使用WKNavigationDelegate,您可以在每次收到响应时获取状态代码。

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,
             decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {

    if let response = navigationResponse.response as? HTTPURLResponse {
        if response.statusCode == 401 {
            // ...
        }
    }
    decisionHandler(.allow)
}

4

HTTPURLResponseURLResponse的子类。在Swift中,“条件下转换”的方式是条件转换as?,这可以与条件绑定if let结合使用:

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,
             decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {

    if let response = navigationResponse.response as? HTTPURLResponse {
        if response.statusCode == 401 {
            // ...
        }
    }
    decisionHandler(.allow)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接