在Xamarin iOS WebView中显示错误

问题描述

如果连接失败,Xamarin Forms WebView控件将显示白色表面。在iOS上,我想显示我可以获得的所有错误信息。

我正在使用此代码覆盖WkWebVieWrenderer:

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview

[assembly: ExportRenderer(typeof(HybridWebView),typeof(HybridWebVieWrenderer))]
namespace Customrenderer.iOS
{
    public class HybridWebVieWrenderer : WkWebVieWrenderer,IWKScriptMessageHandler
    {
        public HybridWebVieWrenderer() : this(new WKWebViewConfiguration())
        {
        }
    }
}

我还发现了此帖子已过时:

https://forums.xamarin.com/discussion/175060/how-can-i-display-a-detailed-error-code-retuned-from-a-webview

如何处理LoadFailed / Connection错误,并使用WkWebVieWrenderer将其显示用户

解决方法

对于 WkWebViewRenderer ,我们需要实现 WKNavigationDelegate

public class HybridWebViewRenderer : WkWebViewRenderer,IWKScriptMessageHandler 
{
    public HybridWebViewRenderer()
    {
    }

    protected override void OnElementChanged(VisualElementChangedEventArgs e)
    {
        base.OnElementChanged(e);

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

    }

    public void DidReceiveScriptMessage(WKUserContentController userContentController,WKScriptMessage message)
    {
        throw new NotImplementedException();
    }
}

public class NavigationDelegate : WKNavigationDelegate
{

    public override void DecidePolicy(WKWebView webView,WKNavigationAction navigationAction,WKWebpagePreferences preferences,Action<WKNavigationActionPolicy,WKWebpagePreferences> decisionHandler)
    {
      //  base.DecidePolicy(webView,navigationAction,preferences,decisionHandler);

        decisionHandler.Invoke(WKNavigationActionPolicy.Allow,preferences);

    }

    public override void DidFailNavigation(WKWebView webView,WKNavigation navigation,NSError error)
    {
        base.DidFailNavigation(webView,navigation,error);

        //...load fail

    }

    public override void DidFinishNavigation(WKWebView webView,WKNavigation navigation)
    {
        base.DidFinishNavigation(webView,navigation);

        //...load success
    }
}