iOS上没有互联网连接的应用程序崩溃

时间:2017-06-06 09:46:22

标签: c# ios xamarin.forms

我使用async方法检索JSON数据,数据成功,但当我在设备中关闭互联网时,应用程序停止运行。如何处理此异常,或者如何在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;
                });



            }

我试过这个,但似乎无法正常工作,我该如何处理呢。

1 个答案:

答案 0 :(得分:2)

使用简单的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;
    });
}