Dani
Dani

Reputation: 13

Xamarin iOS Background task

I am working at a Xamarin Forms app and I am trying to make a background task for iOS. Works only the first time when i'm deploying on the phone. After that when i lock the phone nothing happens. Here is my code :

 nint taskID;
 public void Background()
 {
    new Task(() =>
    {
        taskID = UIApplication.SharedApplication.BeginBackgroundTask(() =>
        {
         UIApplication.SharedApplication.EndBackgroundTask(taskID);
        });

        //what to do

        UIApplication.SharedApplication.EndBackgroundTask(taskID);
    }).Start();
}

Upvotes: 1

Views: 771

Answers (1)

Ranjit
Ranjit

Reputation: 863

BeginBackgroundTask will extend your app’s background execution time ensures that you have adequate time to perform critical tasks.

You can find the extended time using this property UIApplication.SharedApplication.BackgroundTimeRemaining. This is a countdown timer. This value will be reducing when application in background and stops once time expired.

        nint taskID;
        private async Task Background()
        {
            taskID = UIApplication.SharedApplication.BeginBackgroundTask(() => BGTimeExpired());
            await DoYourTask() //Start your task which you wanted to do when application goes to background. If you have already started your task and here just you wanted to extend the background operation time then. Add while loop [while (UIApplication.SharedApplication.BackgroundTimeRemaining > 5) await Task.Delay(1000);]
            
            //if your task completed before background time expired. Then call BGTimeExpired()
            BGTimeExpired();
        }

        private void BGTimeExpired()
        {
            //Safely end your on going task here

            if (taskID != default(nint))
            {
                UIApplication.SharedApplication.EndBackgroundTask(taskID); //End background task
                taskID = default(nint);
            }
        }

        public override void DidEnterBackground(UIApplication application)
        {
            base.DidEnterBackground(application);
            Background();
        }

        public override void WillEnterForeground(UIApplication application)
        {
            base.WillEnterForeground(application);
            if (taskID != default(nint))
            {
                UIApplication.SharedApplication.EndBackgroundTask(taskID);
                taskID = default(nint);
            }
        }

Upvotes: 2

Related Questions