Forum Xamarin.iOS

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

Timer runs slower than actual timespan in Xamarin.ios

SerenaSerena Member ✭✭
edited November 2020 in Xamarin.iOS

I am working on a project show the timer running after user clicks check-in button.

Issue Found:
1. user clicks check-in button, the timer starts working
2. click home button
3. after a while (let say 10 minutes), go back to the application, the timer is shown much less than 10 minutes (6 or 7)

But on Android, the timer is working properly.

key code in viewmodel:

private void InitializeTimer()
        {
            _timer = new Timer();
            _timer.Interval = 1000;
            _timer.Enabled = false;
            _timer.Elapsed += TimerElapsed;
        }

private void TimerElapsed(object sender, ElapsedEventArgs e)
        {
            RunningTotal += TimeSpan.FromSeconds(1);
        }

RunningTotal is the binding property of a label text, to show the latest TimeSpan.

Did anyone meet similar issue before? Is it a bug on IOS?

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    Timer will be stopped after entering the background on iOS. This is by design.
    We could record the time when the app runs into the background and then get the interval when coming back like:

    DateTime sleepDate;
    protected override void OnSleep()
    {
        sleepDate = DateTime.Now;
    }
    
    protected override void OnResume()
    {
        var interval = (DateTime.Now - sleepDate).TotalSeconds;
    }
    

    This value could be more accurate. And you could consume it on your specific page.

  • SerenaSerena Member ✭✭

    @LandLu
    To consume it on a specific page, is it to use event handler like this? Or use messaging center?

    And I also found onAppearing on ios isn't working when coming to foreground from background, while Android is working. I tried methods in this post but no luck. Is there any other way to trigger onAppearing, which may work better for me in my case to deal with the timer. Because I am calculating interval = (DateTime.Now - check-in time).TotalSeconds rather than sleepDate.

  • LandLuLandLu Member, Xamarin Team Xamurai

    To consume it on a specific page, is it to use event handler like this? Or use messaging center?

    Both are OK.

Sign In or Register to comment.