Forum Xamarin Xamarin.Forms

Ask location Permission wait for it and GetLocation when user allows the permission

JunedJuned Member ✭✭

I am new in Xamarin.Forms. I want to ask for the location permission to the user, then if user allows it, get his location. The problem is RequestPermissionAsyn and GetLastKnownLocationAsync, both are async operations. Hence I want to wait till user grants permission and then call the GetLastKnownLocationAsync.

Here is the code I am using

async void AskPermission(object sender, EventArgs e)
{
    await Task.Run(async () =>
    {
        var permissionStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
        if (permissionStatus != PermissionStatus.Granted)
        {
            var response = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);
            var userResponse = response[Permission.Location];
            Debug.WriteLine($"Permission {Permission.Location} {permissionStatus}");
        }
        else
            Debug.WriteLine($"Permission is finally {Permission.Location} {permissionStatus}");
    });

    // Call the GetLocation if user allowed the permission.
}

async void GetLocation()
{
    Location location;
    location = await Geolocation.GetLastKnownLocationAsync();
    Location.Text = location.Latitude.ToString();
}

I can successfully prompt the user for allowing permission, but GetLocation() is not executing. That means even if I write Debug.WriteLine(""); whether permission granted?, I am not getting anything in the output Window. Any Help would be much appreciated. Basically I want to run both the asynchronous operations one after the other. I do not understand whether the problem is with asynchronous operations or whether it needs to run from UI Thread.

Answers

  • JoeMankeJoeManke USMember ✭✭✭✭✭

    Why are you wrapping the permission code in a Task.Run() block?

    Also, change your GetLocation() method to return a Task. Never make an async void method when you don't have to.

  • JohnHardmanJohnHardman GBUniversity admin

    @Juned

    @JoeManke said:
    Why are you wrapping the permission code in a Task.Run() block?

    Also, change your GetLocation() method to return a Task. Never make an async void method when you don't have to.

    And having changed async void methods to async Task, rename them to have an "Async" suffix (so, GetLocation becomes GetLocationAsync). It makes maintaining code easier in future.

Sign In or Register to comment.