Home > Software engineering >  Problem with asking for location permission xamarin c#
Problem with asking for location permission xamarin c#

Time:11-17

I have a question about a final project for school. So I have a problem when asking the permission to request location. When these permissions are ok, the location and frontend are allowed to be shown. When not, an error is shown. The problem is that this function is async, so it does not wait for a response that the location is allowed. Therefore, it shows the error message immediately. Anybody any idea how to solve this? Sincerely.

namespace Eindproject.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Stations : ContentPage
    {
        public Stations()
        {
            InitializeComponent();

            // Check for location permission before getting location
            if (CheckLocationPermission())
            {
                // Load frontend
                frontend();
            }
            else
            {
                // Ask for permission
                RequestLocationPermission();

                // check again
                if (CheckLocationPermission())
                {
                    // Load frontend
                    frontend();
                }
                else
                {
                    // Show error
                    DisplayAlert("Error", "Location permission is required", "OK");
                }
                
            }


        }

        private async void RequestLocationPermission()
        {
            // Ask for permission
            await Permissions.RequestAsync<Permissions.LocationWhenInUse>();

        }

        private bool CheckLocationPermission()
        {
            // Check if permission is granted
            if (PermissionStatus.Granted == Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>().Result)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private async void frontend()
        {
            // Get location
            Location location = await DataRepository.GetLocationAsync();
            // Get stations
            List<IcaoStation> stations = await DataRepository.GetNearbyStationsAsync(location.Latitude, location.Longitude);
            // Set source
            lvwCollectibleItems.ItemsSource = stations;
        }
    }
}

CodePudding user response:

Move the actual code from the constructor to an appropriate event handler for events like Loaded, NavigatedTo or Appearing. Declare these event handlers as async, you can then use await on your async method RequestLocationPermission to defer the following code until a result is available.

You should also declare CheckLocationPermission as async and use await on CheckStatusAsync instead of accessing the Result property of the task.

  • Related