Hello,
I have to send the device gps coordinate to the database in the time interval of 2 minutes for background and foreground mode in IOS xamarin forms?
Here is my code using geolocation plugin :
private async void GetCurrentLocation()
{
try
{
var hasPermission = await Utils.CheckPermissions(Permission.Location);
if (!hasPermission)
return;
if (tracking)
{
CrossGeolocator.Current.PositionChanged -= CrossGeolocator_Current_PositionChanged;
CrossGeolocator.Current.PositionError -= CrossGeolocator_Current_PositionError;
}
else
{
CrossGeolocator.Current.PositionChanged += CrossGeolocator_Current_PositionChanged;
CrossGeolocator.Current.PositionError += CrossGeolocator_Current_PositionError;
}
if (CrossGeolocator.Current.IsListening)
{
await CrossGeolocator.Current.StopListeningAsync();
ImageTick.Source = "cross.png";
await DisplayAlert("Location Denied", "Please enable your GPS(location services)", "OK");
tracking = false;
count = 0;
}
else
{
Positions.Clear();
if (await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(1), 10, true, new Plugin.Geolocator.Abstractions.ListenerSettings
{
ActivityType = Plugin.Geolocator.Abstractions.ActivityType.AutomotiveNavigation,
AllowBackgroundUpdates = true,
DeferLocationUpdates = true,
DeferralDistanceMeters = 1,
DeferralTime = TimeSpan.FromSeconds(1),
ListenForSignificantChanges = true,
PauseLocationUpdatesAutomatically = false
}))
{
ImageTick.Source = "tick.png";
tracking = true;
}
}
}
catch (Exception ex)
{
await DisplayAlert("Uh oh", "Something went wrong, but don't worry we captured for analysis! Thanks.", "OK");
}
}
void CrossGeolocator_Current_PositionError(object sender, PositionErrorEventArgs e)
{
var abc = "Location error: " + e.Error.ToString();
}
void CrossGeolocator_Current_PositionChanged(object sender, PositionEventArgs e)
{
Device.BeginInvokeOnMainThread(() =>
{
var position = e.Position;
Positions.Add(position);
if(position != null)
{
ImageTick.Source = "tick.png";
}
else
{
ImageTick.Source = "cross.png";
DisplayAlert("Location Denied", "Please enable your GPS(location services)", "OK");
}
count++;
DateTime endTime = DateTime.Now;
TimeSpan span = endTime.Subtract(startTime);
Console.WriteLine(span);
if(span.Minutes >= 2)
{
Settings.CurrentLat = position.Latitude.ToString();
Settings.CurrentLon = position.Longitude.ToString();
**SetPosition();**
startTime = endTime;
}
var x = $"{count} updates";
var y = string.Format("Time: {0} \nLat: {1} \nLong: {2} \nAltitude: {3} \nAltitude Accuracy: {4} \nAccuracy: {5} \nHeading: {6} \nSpeed: {7}",
position.Timestamp, position.Latitude, position.Longitude,
position.Altitude, position.AltitudeAccuracy, position.Accuracy, position.Heading, position.Speed);
});
}
as per the above code Kindly give me the solution so that I can run my IOS app in xamarin forms for foreground and background mode.
//Note SetPosition() is the function I am using to hit the API.