iOS WKWebView 加载网页404等 获取状态码

WKWebView 获取状态码

代码如下:

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {

    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithURL:webView.URL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        NSHTTPURLResponse *tmpresponse = (NSHTTPURLResponse*)response;

        NSLog(@"statusCode:%ld", tmpresponse.statusCode);

    }];

    [dataTask resume];

}

拿到状态码之后可以自由做处理。

顺便说一下请求被重定向调用的方法:- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation 。

顺便说一下UIWebView的: 

// 方法一 (9.0已被弃用)

 NSHTTPURLResponse *response = nil;

 [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

 NSLog(@"statusCode:%ld", response.statusCode);

  // 方法二

 NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:webView.request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

   NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;

   NSLog(@"statusCode:%ld", httpResponse.statusCode);

 }];

 [dataTask resume];


文章偏向于笔记,错误之处望指正,谢谢。

你可能感兴趣的:(iOS WKWebView 加载网页404等 获取状态码)