WKWebView 捕获 HTTP 错误代码
WKWebView catch HTTP error codes
当我 return 我的页面出现任何 http 错误时(当前为 401,但我也尝试使用 404 等等)
http://min60.com/__personal/e401.php
WKWebView 的委托回调不会return错误
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
如何捕获此类错误?
关键是等待响应然后检查对象,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);
}
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)
}
当我 return 我的页面出现任何 http 错误时(当前为 401,但我也尝试使用 404 等等)
http://min60.com/__personal/e401.php
WKWebView 的委托回调不会return错误
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
如何捕获此类错误?
关键是等待响应然后检查对象,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);
}
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)
}