我有一个支持 UWP、iOS 和 Android 的 Xamarin.Forms 应用程序。具体来说,我现在正在 Android 模拟器上测试我的应用程序。为了获取位置,我使用 Xamarin.Essentials。这是我的代码片段:
在 PageModel 中:
bu = await GeolocationSrvc.GetBusinessUnitAsync();
这是上面方法的实现:
public static async Task<BusinessUnits> GetBusinessUnitAsync()
{
BusinessUnits bu = BusinessUnits.Aus;
try
{
Location location = await GetLocation().ConfigureAwait(false);
IEnumerable<Placemark> placemarks = await Geocoding.GetPlacemarksAsync(location);
Placemark placemark = placemarks?.FirstOrDefault();
string countryCode = placemark?.CountryCode;
switch (countryCode)
{
case "AQ":
case "AU":
case "NZ":
bu = BusinessUnits.Aus;
break;
default:
bu = BusinessUnits.NA;
break;
}
}
catch (Exception)
{
throw;
}
return bu;
}
private static Task<Location> GetLocation()
{
GeolocationRequest request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
TaskCompletionSource<Location> locationTaskCompletionSource = new TaskCompletionSource<Location>();
Device.BeginInvokeOnMainThread(async () =>
{
locationTaskCompletionSource.SetResult(await Geolocation.GetLocationAsync(request));
});
return locationTaskCompletionSource.Task;
}
当执行到
locationTaskCompletionSource.SetResult(await Geolocation.GetLocationAsync(request));
系统询问我是否要允许该应用获取我的位置。如果我按是,它会按预期工作。但是如果我按否,则永远不会返回该位置(甚至不为空),则永远不会执行以下代码。我希望在回答否的情况下使用设置的默认值
BusinessUnits bu = BusinessUnits.Aus;
但它不会发生。