How to set a custom WKNavigationDelegate while maintaining original functionality

I have implemented a WkWebViewRenderer subclass, trying to disable navigation in certain cases. Based on a discussion on the forums ("Setting delegate of control in custom renderer results in lost functionality" is the title, can't post the link) I take care to save the current NavigationDelegate in a class property.

if (_oldDelegate == null && this.NavigationDelegate != null)
{
    _oldDelegate = (WKNavigationDelegate)this.NavigationDelegate;
}

Then I override all the methods available in the assembly where calling the same method on oldDelegate is allowed, like this:

[Export("webView:didFinishNavigation:")]
public void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{
    _oldDelegate.DidFinishNavigation(webView, navigation);
}

Some of the methods don't let me do this, like the decidePolicyForNavigationResponse one, throwing Foundation.You_Should_Not_Call_base_In_This_Method exception. The Navigating/Navigated events in the PCL seem to be triggered fine without them, but I wonder if it's something missing.

The final step is overriding decidePolicyForNavigationAction method, where I try to set WKNavigationActionPolicy.Cancel:

[Export("webView:decidePolicyForNavigationAction:decisionHandler:")]
public void DecidePolicy(WKWebView webView, WKNavigationAction navigationAction, Action<WKNavigationActionPolicy> decisionHandler)
{
    if (navigationAction.Request.Url.ToString().Equals("customurl"))
    {
        decisionHandler(WKNavigationActionPolicy.Cancel);
    }
    else
    {
        decisionHandler?.Invoke(WKNavigationActionPolicy.Allow);
    }
    _oldDelegate.DecidePolicy(webView, navigationAction, decisionHandler);
}

But the app crashes here _oldDelegate.DecidePolicy(webView, navigationAction, decisionHandler); with the message Completion handler passed to -[WKPrivateNavigationDelegate webView:decidePolicyForNavigationAction:decisionHandler:] was called more than once.

So, my question is, how can I do some custom login by overriding the WebView's delegate methods while keeping the default functionality in the PCL?

Tagged:

Posts

Sign In or Register to comment.