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.
  1. #region background Task
  2. public override void WillEnterForeground(UIApplication application) {
  3. Console.WriteLine("App will enter foreground");
  4. }
  5. // Runs when the activation transitions from running in the background to
  6. // being the foreground application.
  7. public override void OnActivated(UIApplication application) {
  8. // Console.WriteLine("App is becoming active");
  9. }
  10. public override void OnResignActivation(UIApplication application) {
  11. //Console.WriteLine("App moving to inactive state.");
  12. }
  13. public override void DidEnterBackground(UIApplication application) {
  14. //Console.WriteLine("App entering background state.");
  15. nint taskID = 0;
  16. // if you're creating a VOIP application, this is how you set the keep alive
  17. //UIApplication.SharedApplication.SetKeepAliveTimout(600, () => { /* keep alive handler code*/ });
  18. // register a long running task, and then start it on a new thread so that this method can return
  19. taskID = UIApplication.SharedApplication.BeginBackgroundTask(() => {
  20. Console.WriteLine("Running out of time to complete you background task!");
  21. UIApplication.SharedApplication.EndBackgroundTask(taskID);
  22. });
  23. Task.Factory.StartNew(() => FinishLongRunningTask(taskID));
  24. }
  25. void FinishLongRunningTask(nint taskID) {
  26. Console.WriteLine("Starting task {0}", taskID);
  27. Console.WriteLine("Background time remaining: {0}", UIApplication.SharedApplication.BackgroundTimeRemaining);
  28. // sleep for 15 seconds to simulate a long running task
  29. Thread.Sleep(15000);
  30. Console.WriteLine("Task {0} finished", taskID);
  31. Console.WriteLine("Background time remaining: {0}", UIApplication.SharedApplication.BackgroundTimeRemaining);
  32. // call our end task
  33. UIApplication.SharedApplication.EndBackgroundTask(taskID);
  34. }
  35. // [not guaranteed that this will run]
  36. public override void WillTerminate(UIApplication application) {
  37. Console.WriteLine("App is terminating.");
  38. }#endregion