gpt4 book ai didi

c# - 没有互联网连接的iOS应用崩溃

转载 作者:行者123 更新时间:2023-12-01 19:53:13 25 4
gpt4 key购买 nike

我正在使用async方法检索JSON数据,数据成功发送,但是当我关闭设备中的Internet时,该应用程序停止了。如何处理此异常,或者如何处理Xamarin.Forms中的Internet连接。

public partial class MainActivity : ContentPage
{

public ObservableCollection<Adverts> Zoos { get; set; }

public int Count = 0;
public short Counter = 0;
public int SlidePosition = 0;
string heightList;
int heightRowsList = 90;

private const string Url = "http://eamobiledirectory.com/cooperp/Mobile/Mobileapi.aspx?Action=Featured&Country=Uganda";
private const string BaseImageUrl = "http://eamobiledirectory.com/cooperp/Images/app_images/";
private HttpClient _client = new HttpClient();
public ObservableCollection<Adverts> adverts;

public MainActivity()
{
InitializeComponent();



TrendingShows();

if (CrossConnectivity.Current.IsConnected)
{

OnAppearing();
}


else
{

App.Current.MainPage.DisplayAlert("Alert ", "No internet Connection Please", "OK");
}






}
protected override async void OnAppearing()
{

var content = await _client.GetStringAsync(Url);
var adv = JsonConvert.DeserializeObject<List<Adverts>>(content);

adverts = new ObservableCollection<Adverts>(adv);



AdvertsCarousel.ItemsSource = adverts;
// attaching auto sliding on to carouselView
Device.StartTimer(TimeSpan.FromSeconds(18), () =>
{
SlidePosition++;
if (SlidePosition == adverts.Count)
SlidePosition = 0;
AdvertsCarousel.Position = SlidePosition;
return true;
});



}

我尝试了此操作,但似乎不起作用,我该如何处理。

最佳答案

使用简单的try / catch结构,这也有助于解决可能发生的任何其他错误。或者查看Connectivity Plugin。它具有一些方法,属性和事件来确定连接的状态,然后您可以相应地处理内容。

编辑

作为您已编辑问题的跟进;您不需要自己调用OnAppearing。您可以将代码抽象为某种需要刷新数据的方法,也可以找到另一种更适合的方法。

您还应该将支票移近获取数据的位置。例如,更像这样:

protected override async void OnAppearing()
{
adverts = new List<Adverts>();

if (CrossConnectivity.Current.IsConnected)
{
var content = await _client.GetStringAsync(Url);
var adv = JsonConvert.DeserializeObject<List<Adverts>>(content);

adverts = new ObservableCollection<Adverts>(adv);
}
else
{
// TODO: Either show cached adverts here, or hide your carrousel or whatever you want to do when there is no connection
}

AdvertsCarousel.ItemsSource = adverts;

// attaching auto sliding on to carouselView
Device.StartTimer(TimeSpan.FromSeconds(18), () =>
{
SlidePosition++;
if (SlidePosition == adverts.Count)
SlidePosition = 0;
AdvertsCarousel.Position = SlidePosition;
return true;
});
}

关于c# - 没有互联网连接的iOS应用崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44386655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com