WKWebView捕获HTTP错误代码

时间:2015-10-04 17:18:55

标签: ios objective-c cocoa-touch wkwebview

当我从我的页面返回任何http错误时(目前是401,但我也试过404等等)

http://min60.com/__personal/e401.php

WKWebView的委托回调不会返回错误

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {

如何捕获此类错误?

2 个答案:

答案 0 :(得分:34)

关键是等待响应,然后检查对象,在http代码上没有调用错误

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {

    if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {

        NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;
        if (response.statusCode == 401) {

            // here we go

        }

    }
    decisionHandler(WKNavigationResponsePolicyAllow);
}

答案 1 :(得分:0)

Swift 版本:

public func webView(
    _ webView: WKWebView,
    decidePolicyFor navigationResponse: WKNavigationResponse,
    decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void
) {
    if
        let httpResponse = navigationResponse.response as? HTTPURLResponse,
        !(200..<400).contains(httpResponse.statusCode)
    {
        // Do something
    }

    decisionHandler(.allow)
}