问题描述
我正在使用 Xamarin.Forms应用,在其中我需要集成WebView
来管理通过外部URL进行的预订。
所以基本上我已经做到了:
<WebView x:Name="webView" Source="{Binding BookingUrl}"
WidthRequest="1000" HeightRequest="1000">
我想管理用户在打开此页面时可能会遇到的一些错误:无法访问互联网,超时,服务器不可用......
为此,我已使用EventToCommandBehavior
来访问 ViewModel 中的事件Navigating
和Navigating
。
所以我的 XAML 看起来像这样:
<WebView x:Name="webView" Source="{Binding AvilaUrlBooking}"
WidthRequest="1000" HeightRequest="1000">
<WebView.Behaviors>
<behaviors:EventToCommandBehavior
EventName="Navigating"
Command="{Binding NavigatingCommand}" />
<behaviors:EventToCommandBehavior
EventName="Navigated"
Command="{Binding NavigatedCommand}" />
</WebView.Behaviors>
</WebView>
ViewModel 像这样:
public ICommand NavigatingCommand
{
get
{
return new Xamarin.Forms.Command<WebNavigatingEventArgs>(async (x) =>
{
if (x != null)
{
await WebViewNavigatingAsync(x);
}
});
}
}
private Task WebViewNavigatingAsync(WebNavigatingEventArgs eventArgs)
{
if (!IsConnected)
ServiceErrorKind = ServiceErrorKind.NoInternetAccess;
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)
{
IsBusy = false;
IsFirstDisplay = false;
switch (eventArgs.Result)
{
case WebNavigationResult.Cancel:
// TODO - do stuff here
break;
case WebNavigationResult.Failure:
// TODO - do stuff here
break;
case WebNavigationResult.Success:
// TODO - do stuff here
break;
case WebNavigationResult.Timeout:
// TODO - do stuff here
break;
default:
// TODO - do stuff here
break;
}
return Task.CompletedTask;
}
bool isFirstDisplay;
public bool IsFirstDisplay
{
get { return isFirstDisplay; }
set { SetProperty(ref isFirstDisplay,value); }
}
public BookingViewModel()
{
_eventTracker = new AppCenterEventTracker();
IsFirstDisplay = true;
Title = "Booking";
IsConnected = Connectivity.NetworkAccess == NetworkAccess.Internet;
Connectivity.ConnectivityChanged += OnConnectivityChanged;
}
如果我使用正确的URL,则在iOS和Android上一切正常。
但是,如果我使用“错误的” URL(例如,缺少字符),则只能在 Android 上使用:WebNavigationResult.Failure
被WebViewNavigatedAsync()
捕获的情况,但我没有在 iOS 上输入WebViewNavigatedAsync()
。
=>这是正常现象吗?
我实现了“刷新”按钮,以管理“ 无法访问互联网”错误。可通过ToolBarItem
访问此按钮,就像在 ViewModel 中
public void Refresh(object sender)
{
try
{
var view = sender as Xamarin.Forms.WebView;
view.Reload();
}
catch (Exception ex)
{
}
}
但是在这种情况下,在激活“飞行”模式后,我也有两种不同的行为:
- 在 iOS 上,当无法访问互联网时:即使再次可以访问互联网,我也不会输入
WebViewNavigatedAsync()
,然后单击“刷新“按钮,我只经过了WebViewNavigatingAsync()
- 在 Android 上,当无法访问互联网时:我很好地输入
WebViewNavigatedAsync()
,并且当再次可以访问互联网时,我点击“刷新”按钮,我同时通过了WebViewNavigatingAsync()
和WebViewNavigatedAsync()
=>这正常吗?有适当的方法来解决这个问题吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)