How to use Geolocator.RequestAccessAsync in WPF desktop app

2

I've built a WPF app in C# which needs to know the user's location, and currently requires that it be entered manually. I'm using the Desktop Bridge to make it be able to run as a UWP app. When it's running as a UWP app, I want to take advantage of the Windows 10 location API if it is enabled. I'm using the following code to request for location access when the program starts:

public static async void RequestAccess()
{
    var accessStatus = await Windows.Devices.Geolocation.Geolocator.RequestAccessAsync();

    switch (accessStatus)
    {
        case Windows.Devices.Geolocation.GeolocationAccessStatus.Allowed:
            UwpDesktop.hasLocationAccess = true;
            break;
        case Windows.Devices.Geolocation.GeolocationAccessStatus.Denied:
            UwpDesktop.hasLocationAccess = false;
            break;
        case Windows.Devices.Geolocation.GeolocationAccessStatus.Unspecified:
            MessageBox.Show("Failed to access Windows 10 location API", "Error");
            UwpDesktop.hasLocationAccess = false;
            break;
    }
}

However I get the following error when I run my app if the location permission is not enabled for it:

System.Exception: 'Element not found. (Exception from HRESULT: 0x80070490)'

The cause of this error as far as I can tell is that the RequestAccessAsync function needs to be run in the main UWP UI thread. The reason it only happens when the location permission is not enabled is because Windows tries to launch a UWP dialog requesting that the user grant location access, but fails to do so in a Desktop Bridge app.

I'm aware of two solutions to this problem. One would be to launch the Location section of the Settings app and show a messagebox to users asking them to grant location access there, which could work but I would really prefer to use the official API. The other option is to create a new UWP code project and write this code there, and then run it from the WPF app.

Microsoft has some documentation that is supposed to explain how to do the second option, but their examples are complicated and I don't know how to apply them to what I'm trying to do. I don't want to create a XAML UI or a background service, all I need is a way to safely call RequestAccessAsync and return a value based on the outcome. I'm wondering if I really need to create a UWP project to make this behave the way I want, or what the simplest way would be to go about it.

c#
wpf
uwp
geolocation
desktop-bridge
asked on Stack Overflow Aug 26, 2018 by tjohnson

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0