0

I have the following code in my Swift 3 project's main ViewController.swift file. When I call showAgreement(), then it executes without error, but no UI is displayed. How can I get UIAlertController to display?

My ViewController.swift file is defined as:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.showAgreement()
    }

    var alert: UIAlertController?

    func showAgreement() {

        alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
        alert!.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))

        alert!.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in
            switch action.style{
            case .default:
                print("default")

            case .cancel:
                print("cancel")

            case .destructive:
                print("destructive")
            }
        }))

        self.present(alert!, animated: true, completion: {

        })

    }

}

The console output says:

Warning: Attempt to present on whose view is not in the window hierarchy!

JAL
  • 41,701
  • 23
  • 172
  • 300
  • Is there any message in the console? – rmaddy Feb 15 '17 at 21:07
  • Can you show where you're calling `showAgreement()`? – dan Feb 15 '17 at 21:08
  • The console output says: Warning: Attempt to present on whose view is not in the window hierarchy! – Michael Spivey Feb 15 '17 at 21:10
  • That means that ViewController is not the current VC – Andrew McKinley Feb 15 '17 at 21:11
  • That's the ViewController that viewDidLoad() is fired on. How can it not be in the hierarchy or not being shown? I'm new to iOS development. My app shows my Main.storyboard and executes this ViewController.viewDidLoad() and all the buttons work. So I think this ViewController is working, other than not showing the UIAlert. – Michael Spivey Feb 15 '17 at 21:16
  • Can you try calling it from your viewDidAppear() function instead? You may be calling it too early in the VC lifecycle. Use override func viewDidAppear() { } instead. – Shen Feb 15 '17 at 21:25
  • That worked! Moving it to override func viewDidAppear worked. Thanks – Michael Spivey Feb 15 '17 at 21:40

0 Answers0