Here is the code snippet when you need to run a task in background on an iOS device even when user locks his/her iPhone or iPad or iOS device.
Here is the code is written in AppDelegate.cs for background task.
- #region background Task
- public override void WillEnterForeground(UIApplication application) {
- Console.WriteLine("App will enter foreground");
- }
-
-
- public override void OnActivated(UIApplication application) {
-
- }
- public override void OnResignActivation(UIApplication application) {
-
- }
- public override void DidEnterBackground(UIApplication application) {
-
- nint taskID = 0;
-
-
-
- taskID = UIApplication.SharedApplication.BeginBackgroundTask(() => {
- Console.WriteLine("Running out of time to complete you background task!");
- UIApplication.SharedApplication.EndBackgroundTask(taskID);
- });
- Task.Factory.StartNew(() => FinishLongRunningTask(taskID));
- }
- void FinishLongRunningTask(nint taskID) {
- Console.WriteLine("Starting task {0}", taskID);
- Console.WriteLine("Background time remaining: {0}", UIApplication.SharedApplication.BackgroundTimeRemaining);
-
- Thread.Sleep(15000);
- Console.WriteLine("Task {0} finished", taskID);
- Console.WriteLine("Background time remaining: {0}", UIApplication.SharedApplication.BackgroundTimeRemaining);
-
- UIApplication.SharedApplication.EndBackgroundTask(taskID);
- }
-
- public override void WillTerminate(UIApplication application) {
- Console.WriteLine("App is terminating.");
- }#endregion