问题描述
如果连接失败,Xamarin Forms WebView控件将显示白色表面。在iOS上,我想显示我可以获得的所有错误信息。
[assembly: ExportRenderer(typeof(HybridWebView),typeof(HybridWebVieWrenderer))]
namespace Customrenderer.iOS
{
public class HybridWebVieWrenderer : WkWebVieWrenderer,IWKScriptMessageHandler
{
public HybridWebVieWrenderer() : this(new WKWebViewConfiguration())
{
}
}
}
我还发现了此帖子已过时:
如何处理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
}
}