WKWebView decidePolicyForNavigationAction for html page resources

656 Views Asked by At

I have a need to monitor all failed requests from a given web page loaded in WKWebKit. For this, I implemented a simple controller with WKWebView on it and also conformed that controller to WKNavigationDelegate:

- (void)viewDidLoad
{
    [super viewDidLoad];
    webView.navigationDelegate = self;
    NSURL *url = [NSURL URLWithString: @"https://google.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    [webView loadRequest:request];
}

- (void)webView:(WKWebView *)webView
    decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse
    decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    NSLog(@"webView.decidePolicyForNavigationResponse %@", navigationResponse.response);
    decisionHandler(WKNavigationResponsePolicyAllow);
}

- (void)webView:(WKWebView *)webView
    decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
    decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@"webView.decidePolicyForNavigationAction %@", navigationAction.request);
    decisionHandler(WKNavigationActionPolicyAllow);
}

I've also tried to implement custom NSURLProtocol extension but can see there just the initial request as with navigationDelegate:

    [NSURLProtocol registerClass:[TrackingNSURLProtocol class]];

I can see my primary request to the google.com webpage in my output but the children's requests kicked off by that page are not tracked even though they are executed and downloaded by the same WKWebView when the page is loaded (css, js, images, etc).

Is it possible to achieve this kind of tracking with WKWebView (or in general with iOS)?

1

There are 1 best solutions below

3
matt On

Depending on what "failed" means, you might prefer to implement the methods with fail in their names:

func webView(WKWebView, didFail: WKNavigation!, withError: Error)
    Called when an error occurs during navigation.
func webView(WKWebView, didFailProvisionalNavigation: WKNavigation!, withError: Error)
    Called when an error occurs while the web view is loading content.