Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to add timer in Xamarin.iOS?

When I display the page, I need to make requests every one minute to update the data in the table that is presented. I don't know where to add this timer logic, since all controller lifecycle methods should end at the appropriate time - I guess?

Where should I put the timer?

like image 825
nicks Avatar asked Oct 17 '22 16:10

nicks


1 Answers

Since you are saying you need to make request every one minute after you display the page, good solution is to start the timer in ViewWillAppear() method and stop it in ViewWillDisappear() - it will be running just when the ViewController is visible in foreground. Unbinding the OnTimedEvent is important to avoid memory leak.

Is that what you need or do you have some more specific requirement?

Sample code:

class MyViewController : UIViewController
{
    public MyViewController(IntPtr handle)
        : base(handle)
    {
    }

    private Timer timer;
    private bool timerEventBinded;

    public override void ViewWillAppear(bool animated)
    {
         base.ViewWillAppear(animated);
         if (timer == null)
         {
            timer = new Timer();
            timer.Enabled = true;
            timer.Interval = 60000;
         }

         if (!timerEventBinded)
         {
            timer.Elapsed += OnTimedEvent;
            timerEventBinded = true;
         }

         timer.Start();
    }

    public override void ViewWillDisappear(bool animated)
    {
        if (timer != null)
        {
           timer.Stop();
           if (timerEventBinded)
           {
              timer.Elapsed -= OnTimedEvent;
              timerEventBinded = false;
           }
           timer = null;
        }

        base.ViewWillDisappear(animated);
    }

    private void OnTimedEvent(Object src, ElapsedEventArgs e)
    {
        //do your stuff
    }
}
like image 115
David Riha Avatar answered Oct 21 '22 03:10

David Riha