Andrea Troccolo
Andrea Troccolo

Reputation: 21

PopModalAsync in OnAppearing Xamarin.Forms

I'm developing an xamarin.forms app.

On a page before starting a video I have to check that the internet connection is turned on otherwise I show an error message and then I have to close the page.

I wrote this code but it doesn't work, the popup is shown, but after i press "ok" the application freezes and it doesn't work anymore.

    private void ContentPage_Appearing(object sender, EventArgs e)
    {
        if (Connectivity.NetworkAccess != NetworkAccess.Internet)
        {
            DisplayAlert("WARNING!", "Error message!", "OK");
            Navigation.PopModalAsync();
        }
        else
        {

            //...

        }
    }

The control is done in the content page's OnAppearing event, is that why Navigation.PopModalAsync() doesn't work? How can I fix it?

Upvotes: 0

Views: 1218

Answers (1)

xerx
xerx

Reputation: 119

You should use asynchronous operations since both DisplayAlert and PopModalAsync return a task. Also you should override page's OnAppearing method and remove the Appearing event handler.

protected override async void OnAppearing()
{
    base.OnAppearing();
    if (Connectivity.NetworkAccess != NetworkAccess.Internet)
    {
        await DisplayAlert("WARNING!", "Error message!", "OK");
        await Navigation.PopModalAsync();
    }
    else
    {

        //...

    }
}

Again using async void is not recommended and I would suggest using MVVM and not write your code directly on the page's codebehind but this should work for now.

Upvotes: 2

Related Questions