Xamarin.Forms DependencyService difficulty getting location

佐手、 提交于 2019-12-03 16:27:14

I would do a slight modification since best practice is to either do all async or none. When you try to return the result from an async method from a non async method you can run into problems with deadlocks. Also, since you aren't using the await keyword when calling the GetPosition method, you are getting back a Task, but aren't checking when the operation is complete. I suggest slightly modifying your code as such.

public interface ICurrentLocation {
    Task<MyLocation> GetCurrentLocation();
}

public async Task<MyLocation> GetCurrentLocation()
{
    var position = await GetPosition();
    return new MyLocation()
    {
        Latitude = position.Latitude,
        Longitude = position.Longitude
    };
}

async Task<Location> GetPosition()
{
    try
    {
          locator = new Geolocator(this) { DesiredAccuracy = 50 };
          if (locator.IsListening != true)
                locator.StartListening(minTime: 1000, minDistance: 0);

          return await locator.GetPositionAsync(timeout: 20000);

    }
    catch (Exception e)
    {
        Log.Debug("GeolocatorError", e.ToString());
    }
}

You aren't waiting for the position function to finish. Many different options and keeping it async is the best one but if you want it synchronous then try this blocking call:

   void GetPosition()
   {
       try
       {
             locator = new Geolocator(this) { DesiredAccuracy = 50 };
             if (locator.IsListening != true)
                   locator.StartListening(minTime: 1000, minDistance: 0);

             position = locator.GetPositionAsync(timeout: 20000).Result;

       }
       catch (Exception e)
       {
           Log.Debug("GeolocatorError", e.ToString());
       }
   }

I also recommend taking a look at Xamarin.Forms.Labs as it already has abstracted GPS service and working sample that is functional for all 3 platforms:

https://github.com/XForms/Xamarin-Forms-Labs

Arthur Csertus

Try adding the assembly above the namespace and awaiting the GetPosition method.

Take a look at this image: http://developer.xamarin.com/guides/cross-platform/xamarin-forms/dependency-service/Images/solution.png

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!