ayushmaan lavania
ayushmaan lavania

Reputation: 21

Timer to show seconds, minutes and hours in iOS Xamarin

I am working on iOS Application in Xamarin.

timer1 = new System.Timers.Timer();
timer1.Interval = 1000;

//Play.TouchUpInside += (sender,e)=>
//{
       timer1.Enabled = true;
       Console.WriteLine("timer started");
       timer1.Elapsed += new ElapsedEventHandler(OnTimeEvent);
//}

This is what i have written in viewdidload();

public void OnTimeEvent(object source, ElapsedEventArgs e)
{
    count++;
    Console.WriteLine("timer tick");
    if (count == 30)
    {
        timer1.Enabled = false;
        Console.WriteLine("timer finished");

        new System.Threading.Thread(new System.Threading.ThreadStart(() =>
        {
            InvokeOnMainThread(() =>
            {
                StartTimer.Text = Convert.ToString(e.SignalTime.TimeOfDay); // this works!
            });
        })).Start();
    }

    else
    {
        //adjust the UI
        new System.Threading.Thread(new System.Threading.ThreadStart(() =>
        {
            InvokeOnMainThread(() =>
            {
                StartTimer.Text = Convert.ToString(e.SignalTime.TimeOfDay); // this works!
            });
        })).Start();

        timer1.Enabled = false;
        Console.WriteLine("timer stopped");
    }
}

This is the event I have called when I clicked on button play. I want this method to keep running so that time get updated on the label (starttimer.Text) in the UI. Like Runnable Interface we use in Android, what do we have to use in iOS to keep it running?

Upvotes: 2

Views: 5090

Answers (2)

Marcel
Marcel

Reputation: 2158

Use async - much cleaner (no marshalling to get you back on the main thread again!)

private int _duration = 0;

public async void StartTimer() {
    _duration = 0;

    // tick every second while game is in progress
    while (_GameInProgress) {
        await Task.Delay (1000);
        _duration++;

        string s = TimeSpan.FromSeconds(_duration).ToString(@"mm\:ss");
        btnTime.SetTitle (s, UIControlState.Normal);
    }
}

Upvotes: 7

Milen
Milen

Reputation: 8867

//before loading the view
public override void ViewWillAppear(bool animated)
{
    ...
    StartTimer();
}
// when view is loaded  
public override void ViewDidLoad()
{
    base.ViewDidLoad();
    ....
    UpdateDateTime();
}

private void UpdateDateTime()
{
    var dateTime = DateTime.Now;
    StartTimer.Text = dateTime.ToString("HH:mm:ss");
}

private void StartTimer()
{
    var timer = new Timer(1000);
    timer.Elapsed += (s, a) => InvokeOnMainThread(UpdateDateTime);
    timer.Start();
}

Upvotes: 4

Related Questions