根据以下链接,我发现了另一种似乎可行的方法:
这可能并不完美,尤其是当我需要从 ViewModel 访问所需的事件时。
所以我创建了一个继承自WebView 的CustomWebView 控件:
public class CustomWebView : WebView
{
public static readonly BindableProperty UriProperty = BindableProperty.Create(
propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(CustomWebView),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
public CustomWebViewErrorKind ErrorKind { get; set; }
public event EventHandler LoadingStart;
public event EventHandler LoadingFinished;
public event EventHandler LoadingFailed;
/// <summary>
/// The event handler for refreshing the page
/// </summary>
public EventHandler OnRefresh { get; set; }
public void InvokeCompleted()
{
if (this.LoadingFinished != null)
{
ErrorKind = WebViewErrorKind.None;
this.LoadingFinished.Invoke(this, null);
}
}
public void InvokeStarted()
{
if (this.LoadingStart != null)
{
ErrorKind = WebViewErrorKind.None;
this.LoadingStart.Invoke(this, null);
}
}
public void InvokeFailed(CustomWebViewErrorKind errorKind)
{
if (this.LoadingFailed != null)
{
ErrorKind = errorKind;
this.LoadingFailed.Invoke(this, null);
}
}
/// <summary>
/// Refreshes the current page
/// </summary>
public void Refresh()
{
OnRefresh?.Invoke(this, new EventArgs());
}
}
然后我有自定义CustomWebView 行为的CustomWkWebViewRenderer:
[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWkWebViewRenderer))]
namespace MyProject.iOS.Renderers
{
public class CustomWkWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>
{
public CustomWkWebViewRenderer()
{
Debug.WriteLine($"CustomWkWebViewRenderer - Ctor");
}
WKWebView webView;
protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
{
base.OnElementChanged(e);
Debug.WriteLine($"CustomWkWebViewRenderer - OnElementChanged()");
if (Control == null)
{
Debug.WriteLine($"CustomWkWebViewRenderer - OnElementChanged() - Control == null");
webView = new WKWebView(Frame, new WKWebViewConfiguration()
{
MediaPlaybackRequiresUserAction = false
});
webView.NavigationDelegate = new DisplayWebViewDelegate(Element);
SetNativeControl(webView);
Element.OnRefresh += (sender, ea) => Refresh(sender);
}
if (e.NewElement != null)
{
Debug.WriteLine($"CustomWkWebViewRenderer - OnElementChanged() - e.NewElement != null");
Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.Uri)));
webView.NavigationDelegate = new DisplayWebViewDelegate(Element);
SetNativeControl(webView);
}
}
private void Refresh(object sender)
{
Debug.WriteLine($"CustomWkWebViewRenderer - Refresh()");
Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.Uri)));
}
}
}
我还有为这个渲染器实现WKNavigationDelegate 的CustomWkWebViewNavigationDelegate:
public class CustomWkWebViewNavigationDelegate : WKNavigationDelegate
{
private CustomWebView element;
public CustomWkWebViewNavigationDelegate(CustomWebView element)
{
Debug.WriteLine($"CustomWkWebViewNavigationDelegate - Ctor");
this.element = element;
}
public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{
Debug.WriteLine($"CustomWkWebViewNavigationDelegate - DidFinishNavigation");
element.InvokeCompleted();
//base.DidFinishNavigation(webView, navigation);
}
public override void DidStartProvisionalNavigation(WKWebView webView, WKNavigation navigation)
{
Debug.WriteLine($"CustomWkWebViewNavigationDelegate - DidStartProvisionalNavigation");
element.InvokeStarted();
//base.DidStartProvisionalNavigation(webView, navigation);
}
[Export("webView:didFailProvisionalNavigation:withError:")]
public override void DidFailProvisionalNavigation(WKWebView webView, WKNavigation navigation, NSError error)
{
Debug.WriteLine($"CustomWkWebViewNavigationDelegate - DidFailProvisionalNavigation - error : {error}");
var errorKind = CustomWebViewErrorKind.None;
switch (error.Code)
{
case -1009: // no internet access
{
errorKind = CustomWebViewErrorKind.NoInternetAccess;
break;
}
case -1001: // timeout
{
errorKind = CustomWebViewErrorKind.Timeout;
break;
}
case -1003: // server cannot be found
case -1100: // url not found on server
default:
{
errorKind = CustomWebViewErrorKind.Failure;
break;
}
}
element.InvokeFailed(errorKind);
//base.DidFailProvisionalNavigation(webView, navigation, error);
}
}
有一个CustomWebViewErrorKind 枚举可以让我在 ViewModel 中实现常见的错误管理:
public enum CustomWebViewErrorKind
{
None = 0,
NoInternetAccess = 1,
Failure = 2,
Timeout = 3,
Cancel = 8,
Other = 9
}
要从 ViewModel 访问事件,我使用 EventToCommandBehavior 就像描述的 there
所以,我已经像这样从视图中公开了所有命令:
<controls:CustomWebView x:Name="webView"
Source="{Binding MyUrlBooking}"
Uri="{Binding MyUrlBooking}"
WidthRequest="1000" HeightRequest="1000">
<WebView.Behaviors>
<behaviors:EventToCommandBehavior
EventName="Navigating"
Command="{Binding NavigatingCommand}" />
<behaviors:EventToCommandBehavior
EventName="Navigated"
Command="{Binding NavigatedCommand}" />
<behaviors:EventToCommandBehavior
EventName="LoadingStart"
Command="{Binding LoadingStartCommand}" />
<behaviors:EventToCommandBehavior
EventName="LoadingFinished"
Command="{Binding LoadingFinishedCommand}" />
<behaviors:EventToCommandBehavior
EventName="LoadingFailed"
Command="{Binding LoadingFailedCommand}"
CommandParameter="{x:Reference webView}"
/>
</WebView.Behaviors>
</controls:CustomWebView>
最后,在我的 ViewModel 中,我为 Android 部分执行此操作:
public ICommand NavigatingCommand
{
get
{
return new Xamarin.Forms.Command<WebNavigatingEventArgs>(async (x) =>
{
if (x != null)
{
await WebViewNavigatingAsync(x);
}
});
}
}
private Task WebViewNavigatingAsync(WebNavigatingEventArgs eventArgs)
{
Debug.WriteLine($"BookingViewModel - WebViewNavigatingAsync()");
IsBusy = true;
return Task.CompletedTask;
}
public ICommand NavigatedCommand
{
get
{
return new Xamarin.Forms.Command<WebNavigatedEventArgs>(async (x) =>
{
if (x != null)
{
await WebViewNavigatedAsync(x);
}
});
}
}
private Task WebViewNavigatedAsync(WebNavigatedEventArgs eventArgs)
{
Debug.WriteLine($"BookingViewModel - WebViewNavigatedAsync()");
IsBusy = false;
switch (eventArgs.Result)
{
case WebNavigationResult.Cancel:
Debug.WriteLine($"BookingViewModel - WebViewNavigatedAsync() - Cancel");
ErrorKind = CustomWebViewErrorKind.Cancel;
break;
case WebNavigationResult.Failure:
default:
Debug.WriteLine($"BookingViewModel - WebViewNavigatedAsync() - Failure");
IsConnected = Connectivity.NetworkAccess == NetworkAccess.Internet;
if (IsConnected)
{
Debug.WriteLine($"BookingViewModel - WebViewNavigatedAsync() - Failure : Failure");
ErrorKind = CustomWebViewErrorKind.Failure;
}
else
if (IsConnected)
{
Debug.WriteLine($"BookingViewModel - WebViewNavigatedAsync() - Failure : NoInternetAccess");
ErrorKind = CustomWebViewErrorKind.NoInternetAccess;
}
break;
case WebNavigationResult.Success:
Debug.WriteLine($"BookingViewModel - WebViewNavigatedAsync() - Success");
ErrorKind = CustomWebViewErrorKind.None;
IsFirstDisplay = false;
break;
case WebNavigationResult.Timeout:
Debug.WriteLine($"BookingViewModel - WebViewNavigatedAsync() - Timeout");
ErrorKind = CustomWebViewErrorKind.Timeout;
break;
}
return Task.CompletedTask;
}
我在 iOS 部分这样做:
public ICommand LoadingStartCommand
{
get
{
return new Xamarin.Forms.Command(async () =>
{
await WebViewLoadingStartAsync();
});
}
}
private Task WebViewLoadingStartAsync()
{
Debug.WriteLine($"BookingViewModel - WebViewLoadingStartAsync()");
IsBusy = true;
return Task.CompletedTask;
}
public ICommand LoadingFinishedCommand
{
get
{
return new Xamarin.Forms.Command(async () =>
{
await WebViewLoadingFinishedAsync();
});
}
}
private Task WebViewLoadingFinishedAsync()
{
Debug.WriteLine($"BookingViewModel - WebViewLoadingFinishedAsync()");
IsBusy = false;
return Task.CompletedTask;
}
public ICommand LoadingFailedCommand
{
get
{
return new Xamarin.Forms.Command<object>(async (object sender) =>
{
if (sender != null)
{
await WebViewLoadingFailedAsync(sender);
}
});
}
}
private Task WebViewLoadingFailedAsync(object sender)
{
Debug.WriteLine($"BookingViewModel - WebViewLoadingFailedAsync()");
var view = sender as CustomWebView;
var error = view.ErrorKind;
Debug.WriteLine($"BookingViewModel - WebViewLoadingFailedAsync() - error : {error}");
IsBusy = false;
return Task.CompletedTask;
}
像这样我能够管理错误、重试并从 ViewModel 刷新,即使它可能不是更好的解决方案...