Reputation: 78
While building my xamarin app I noticed a rather strange behaviour on xamarin.ios. I'm using the geolocator.plugin to find my location and than ofcourse I use this location as I need it through the app. Everything works fine in xamarin.android project but in the xamarin.ios the stops as soon as I call the service on which I find the location. This is a sample of my code:
service.cs
public async Task<Plugin.Geolocator.Abstractions.Position> GetDeviceCurrentLocation()
{
try
{
var locator = Plugin.Geolocator.CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(3));
if (position != null)
{
return position;
}
}
catch (Exception ex)
{
Debug.WriteLine("Unable to get location, may need to increase timeout: " + ex);
}
return new Plugin.Geolocator.Abstractions.Position();
}
and this is my MyViewExample.xaml.cs
public partial class MyViewExample : ContentPage
{
public MyViewExample()
{
InitializeComponent();
Service cs = new Service();
var myLocation = Task.Run(() => api.GetDeviceCurrentLocation()).Result;
var myLatitude = myLocation.Latitude;
var myLongitude = myLocation.Longitude;
Debug.Writeline("Latitude is : " + myLatitude + " and Longitude is : " + myLongitude);
}
}
this is my info.plist file :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
--
--
--
--
--
--
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs access location when open and in the background</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Need location for geolocator plugin</string>
<key>RequestWhenInUseAuthorization</key>
<string>Need location for geolocator plugin</string>
<key>CFBundleIdentifier</key>
<string>my.app.development</string>
</dict>
</plist>
Can anyone give me any clue on why I'm having trouble on getting location on xamarin.ios? Am I forgetting something? I've gone through numerous examples but none worked for me. Any idea on how can I approach at this problem? Any help would be crucial and highly appreciated :). Thanks in advance!
Upvotes: 1
Views: 938
Reputation: 78
Since my task was async, I needed to await
this task. But instead of await-ing it I used this line of code to run the task on the main thread.
var myLocation = Task.Run(() => cs.GetDeviceCurrentLocation()).Result;
And this was the problem with my app. Looks like xamarin.ios doesn't support this kind of "hack". As soon as I made an another method asynchronus and used this line
var myLocation = await cs.GetDeviceCurrentLocation();
everything worked like charm. Hope it helps others looking for an answer of the same problem :)
Upvotes: 1