0

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)?

Mando
  • 11,414
  • 17
  • 86
  • 167

1 Answers1

1

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.
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Failed means http code 4xx, 5xx, and I’ll check it i the decidePolicy handler. The issue is that requests are not getting there (request to all the css, js, images from that page) – Mando Aug 18 '20 at 00:30
  • 1
    No, that's true, css and js and images are not a form of navigation. It sounds like what you need is to inject an event listener. – matt Aug 18 '20 at 01:11
  • do you mean to inject something into the webpage (like additional javascript) to communicate back to the host webview, or update the WKWebView setup to get additional requests information? – Mando Aug 18 '20 at 17:33