我正在努力将geolocator plugin集成到我的Xamarin.Forms应用中。我已经将nuget软件包安装到.core,.droid和amp; .IOS。我没有在解决方案中添加其他项目,因为我在Mac上并且不支持它们。
我添加了示例代码段(减少打印到控制台行),但是它会引发编译器错误。我在顶部添加了using Geolocator;
,但var position
行引发了错误 - the 'await' operator can only be used when its containing method is marked with the 'async' modifier
- 我做错了什么?
我在下面添加了一个屏幕截图:
[![编译器错误] [1]] [1]
任何想法都会非常感激。
我的代码现在运行,我有以下结构:
namespace MyApp
{
public partial class HomePage : ContentPage
{
// Class Definitions
public HomePage(IAdapter adapter)
{
InitializeComponent();
this.adapter = adapter;
var LocManager = new CLLocationManager();
LocManager.AuthorizationChanged += (sender, args) => {
Debug.WriteLine ("Authorization changed to: {0}", args.Status);
};
if (UIDevice.CurrentDevice.CheckSystemVersion(8,0))
LocManager.RequestAlwaysAuthorization();
NewDeviceButton.Clicked += async (sender, e) => {
//Code which I would like to be able to use GetLatitude.
}
}
async Task<double> GetLongitude()
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
var longitude = position.Longitude;
return longitude;
}
}
但是,我收到以下错误消息。
On iOS 8.0 and higher you must set either NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription in your Info.plist file to enable Authorization Requests for Location updates!
我最初只使用了异步方法,但看到了错误消息并阅读了应用说明,我在顶部添加了额外的代码来尝试授权位置服务。但是,我现在收到一条错误消息,上面显示Error CS0246: The type or namespace name 'CLLocationManager' could not be found. Are you missing an assembly reference? (CS0246)
这显示在var LocManager行上。为什么这是我应该怎么做才能解决它?
答案 0 :(得分:0)
正常的await方法需要在异步方法中运行。
因此,您需要在OS项目中调用您的方法。
这里使用geolocator插件的步骤:
在xamarin表单项目上创建一个接口:
public interface ILocation
{
Task<Position> GetLocation();
}
在您的操作系统项目(Android,IOS或WP)中创建一个类
这里是Android的例子
public class Location_Android : Activity, ILocation
{
public async Task<Position> GetLocation()
{
return await GetPosition();
}
private async Task<Position> GetPosition()
{
Position result = null;
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
if (locator.IsListening != true)
{
locator.StartListening(minTime: 1000, minDistance: 0);
}
var position = await locator.GetPositionAsync(10000);
//You can use Xamarin.Forms.Maps.Position
//Here I use a personnal class
result = new Position(position.Longitude, position.Latitude);
}
catch (Exception e)
{
Log.Debug("GeolocatorError", e.ToString());
}
return result;
}
}
在课堂上调用类似
的方法var position = await DependencyService.Get<ILocation>().GetLocation();
希望这可以帮到你。