Search code examples
c#timerxamarin.ios

Message not updated in UIAlertController using a Timer


I'm trying to add a countdown timer message in the UIAlertController, the timer fires correctly and logs in the console everytime it fires up. However the alertController's message is not updated. I tried updated the message outside of the Timer it works. Not sure why it does not work inside the timer. Here's my code:

var ttimer = new System.Timers.Timer(1000);

alertController = UIAlertController.Create("title", "initial message", UIAlertControllerStyle.Alert);
using (var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (t) => { ttimer.Stop(); ttimer.Dispose(); }))
{
    alertController.AddAction(cancelAction);
}
PresentViewController(alertController, true, null);

var counter = 5; // 5 seconds count down timer, dismiss alert after 5 seconds

ttimer.Elapsed += (Object source, ElapsedEventArgs e) =>
{
    Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
        e.SignalTime); // This logs to the console fine
    if (counter > 0)
    {
        counter--;
        alertController.Message ="new message"; // This doesn't work
    }
    else
    {
        alertController.DismissViewController(false, null); // This doesn't work
        ttimer.Stop();
        ttimer.Dispose();
    }
};

ttimer.AutoReset = true;
ttimer.Enabled = true;

alertController.Message = "new message for testing"; // This works

What did I do wrong? This is in Xamarin iOS/C#.


Solution

  • the Elapsed event is not occuring on the main thread. You can force your UI update to use the UI thread

    InvokeOnMainThread ( () => {
      alertController.Message ="new message";
    });