I'm trying to get background tasks to work on IOS using c# and visual studio. I'm using the BGTaskScheduler framework. I first register a task when the app goes into background mode then it should hit after 2 minutes by setting:
EarliestBeginDate = (NSDate)DateTime.Now.AddMinutes(2)
The task is never triggered, so it's like the background tasks are not aware of the scheduled task. Has someone had a similar issue before? I'm using c# because I want most code to be the same on IOS and Android, if I do similar coding using SWIFT and xcode then it does work, just in Visual Studio using c# it does not work. Here is the code, its on github. :
GitHub - sigthor/background.ping[
^]
What I have tried:
This is my schedule proc:
private void ScheduleAppPing()
{
try
{
Analytics.TrackEvent("Scheduling location background task", new Dictionary<string, string> { { "user", App.User?.Id } });
Debug.WriteLine("Scheduling location background task.");
var request = new BGAppRefreshTaskRequest(PingTaskId)
{
EarliestBeginDate = null
};
BGTaskScheduler.Shared.Submit(request, out NSError error);
if (error != null)
{
throw new Exception(error.LocalizedDescription);
}
}
catch (Exception ex)
{
Crashes.TrackError(ex);
Debug.WriteLine($"Error while trying to schedule a background task.: [{ex.Message}]");
}
}
and this is my handleapping event that should be called
private void HandleAppPing(BGAppRefreshTask task)
{
ScheduleAppPing();
task.ExpirationHandler = () =>
{
task.SetTaskCompleted(false);
urlSession.GetAllTasks((tasks) =>
{
tasks.ForEach(t =>
{
t.Cancel();
});
urlSession.InvalidateAndCancel();
});
};
Debug.WriteLine("Location ping started.");
Analytics.TrackEvent("Location background task started", new Dictionary<string, string> { { "user", App.User?.Id } });
try
{
var location = App.User?.LastLocation;
if (location != null)
{
var url = service.GenerateUpdateLocationUrl(App.User?.Id, location.Longitude, location.Latitude);
Analytics.TrackEvent("Location background url", new Dictionary<string, string> { { "user", App.User?.Id }, { "url", url } });
var urlRequest = NSUrlRequest.FromUrl(NSUrl.FromString(url));
urlSession.CreateDataTask(urlRequest, (data, response, error) => {
if (error != null)
{
var ex = new Exception(error.LocalizedDescription);
Crashes.TrackError(ex);
Debug.WriteLine($"Error while sending location in a background task.: [{ex.Message}]");
task.SetTaskCompleted(false);
}
else
{
task.SetTaskCompleted(true);
}
});
}
else
{
Analytics.TrackEvent("Location background task is missing the location!", new Dictionary<string, string> { { "user", App.User?.Id } });
task.SetTaskCompleted(false);
}
}
catch (Exception ex)
{
Crashes.TrackError(ex);
Debug.WriteLine("Error while updating location in scheduled background task.");
task.SetTaskCompleted(false);
}
}