Attempt to present <UIAlertController: 0x7a922200> on * whose view is not in the window hierarchy

Hi,

I'm trying to present an UIAlertController with a countdown timer. The code works fine if it is in my ViewController.cs file but if I try to move it to a separate class (SessionManager.cs), I get the error in the title. Does anyone have any suggestions on how to fix this issue? My code as below:

ViewController.cs
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);

        var sessManager = new SessionManager();

        sessManager.showAlert();
    }

SessionManager.cs
public class SessionManager : UIViewController
{
int counter = 600;
NSTimer timer;
UIAlertController alertCon;

        public SessionManager()
        {
        }

        public void showAlert()
        {
            //var alertController = UIAlertController.Create("Title", "aaa", UIAlertControllerStyle.Alert);
            alertCon = UIAlertController.Create("Title", counter + "seconds", UIAlertControllerStyle.Alert);
            alertCon.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));

            PresentViewController(alertCon, true, null);

        }

        public override void PresentViewController(UIViewController viewControllerToPresent, bool animated, Action completionHandler)
        {
            base.PresentViewController(viewControllerToPresent, animated, completionHandler);

            this.timer = NSTimer.CreateScheduledTimer(1, this, new ObjCRuntime.Selector("decrease"), null, true);

        }

        [Export("decrease")]
        public void decrease()
        {
            int seconds = 0;
            //int minutes = 0;

            if (counter > 0)
            {
                counter -= 1;
                alertCon.Message = counter.ToString() + " Seconds";

            }
            else
            {
                DismissViewController(true, null);
                timer.Invalidate();
            }
        }
    }
Sign In or Register to comment.