question

SibalikMike-8717 avatar image
0 Votes"
SibalikMike-8717 asked SibalikMike-8717 commented

WebView Navigated event not firing consistently on iOS

I have a page that has a WebView and an ActivityIndicator. I've wired up event handlers to to the WebView Navigating and Navigated events to activate and de-activate the ActivityIndicator. This all works great on Android. On iOS, the Navigating event fires, but the Navigated event does not fire consistently. This often leaves the ActivityIndicator in a perpetually activated state. Has anyone found a fix or workaround that doesn't involve a custom WebView render?

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

ColeXia-MSFT avatar image
1 Vote"
ColeXia-MSFT answered SibalikMike-8717 commented

Hello,

Welcome to Microsoft Q&A!

WebView.Navigated event is raised after navigation completes , it may not triggered if the request failed .

We can create a custom renderer for WebView and hack the event when loading finish(successful/failed) .

Then send a message to stop the ActivityIndicator in Forms project .


Custom Renderer in iOS


[assembly: ExportRenderer(typeof(WebView), typeof(MyWebRenderer))]
namespace FormsA.iOS
{

    public class MyDelegate : WKNavigationDelegate
    {
        public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
        {

            MessagingCenter.Send<object>(this, "End");
        }

        public override void DidFailNavigation(WKWebView webView, WKNavigation navigation, NSError error)
        {
            MessagingCenter.Send<object>(this, "End");
        }
    }
    class MyWebRenderer : WkWebViewRenderer 
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            if(e.NewElement != null)
            {
                this.NavigationDelegate = new MyDelegate();
            }
        }
    }

}


Forms



MessagingCenter.Subscribe<object>(this, "End", (sender) => {
     indicator.IsRunning = false;
});


If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks! This worked.

0 Votes 0 ·

Originally, this worked but it has stopped working. Perhaps the change over to WKWebView or upgrade to Xamarin Forms 5 might have had something to with it. DidFinishNavigation still fires in the custom renderer, but now Navigating and Navigated never fire on the WebView.

0 Votes 0 ·