2015-10-04 165 views
12

當我返回任何HTTP錯誤從我的頁面(目前爲401,但我也試圖與404等)WKWebView抓HTTP錯誤代碼

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 { 

如何捕捉這樣的錯誤?

回答

27

的關鍵是等待響應,然後檢查對象,沒有錯誤被稱爲在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); 
}