Forum Xamarin Xamarin.Forms

iOS webview - custom renderer which uses WkWebView

MikilllMikilll Member ✭✭✭

Hello,
I started working on writing a custom renderer for webview on iOS. I want to use WkWebView instead of UIWebView.

I know that Xamarin.Forms provides an option to substitute UIWebView with WkWebView, but there is an unresolved bug in it.

Here it is:
https://github.com/xamarin/Xamarin.Forms/issues/8028

In this GIthub thread @jfversluis provided a solution to this bug:

using System;
using Xamarin.Forms;

namespace App1
{
    public class MyWebView : WebView
    {
    }
}

Consume it, again in your shared project, like this:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:app1="clr-namespace:App1"
             mc:Ignorable="d"
             x:Class="App1.MainPage">

    <app1:MyWebView Source="https://sollers.eu"/>

</ContentPage>

Then, in your iOS project, create a custom renderer like this`

using System;
using App1;
using App1.iOS;
using Foundation;
using WebKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(MyWebView), typeof(MyWebViewRenderer))]
namespace App1.iOS
{
    public class MyWebViewRenderer : WkWebViewRenderer, IWKNavigationDelegate
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            NavigationDelegate = this;
        }

        [Export("webView:decidePolicyForNavigationAction:decisionHandler:")]
        public void DecidePolicy(WKWebView webView, WKNavigationAction navigationAction, Action<WKNavigationActionPolicy> decisionHandler)
        {
            if (navigationAction.TargetFrame == null)
            {
                webView.LoadRequest(navigationAction.Request);
            }

            decisionHandler.Invoke(WKNavigationActionPolicy.Allow);
        }
    }
}

However, when using this code Navigating and Navigated events are not called. Does anyone have a solution on how to easily implement these events in WkWebView renderer?

Sign In or Register to comment.