Click here to Skip to main content
14,733,890 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 = (NSDate)DateTime.Now.AddMinutes(2) // Fetch no earlier than 10 minutes from now
                   //EarliestBeginDate = (NSDate)DateTime.Now.AddSeconds(30) // Fetch no earlier than 10 minutes from now
                   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)
        {
            // Schedule the next task (Periodic scheduling)
            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);
            }
        }
Posted
Updated 23-Oct-20 7:48am
v2
Comments
Gerry Schmitz 23-Oct-20 14:53pm
   
What's wrong with the .NET Backgroundworker?
Ravi Bhavnani 23-Oct-20 18:43pm
   
I think the OP wants code to run when the app is backgrounded, which I believe is different from BackgroundWorker (which runs code in a thread other than the main UI thread).

/ravi
Gerry Schmitz 24-Oct-20 0:34am
   
You're only partly informed. BGW can update the UI thread via the ProgressChanged event.
Ravi Bhavnani 24-Oct-20 10:46am
   
I thought a BGW that was initiated by the app's UI won't execute when the app is backgrounded, although a Service would continue to execute. Perhaps I'm mistaken?

/ravi
Gerry Schmitz 24-Oct-20 12:47pm
   
A window is "active" or not (it has or has not got focus); it is NOT "backgrounded". BGW can update a Window whether it has focus or not: it's just "properties". You need to stick with terms that you understand.
Ravi Bhavnani 25-Oct-20 10:57am
   
Thanks for the clarification. I guess the app would become backgrounded only when the activity's state is "stopped".

/ravi

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900