Search code examples
iosswiftuialertcontroller

Cannot present UIAlertController in swift


I've this function

func showMessageNew(msg:String,title: String){
        let alertController = UIAlertController(title: title, message: msg, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default)
        alertController.addAction(okAction)
        self.present(alertController, animated: true)
}

But when I run it I've this in the console: whose view is not in the window hierarchy!


Solution

  • Below code can be used to present the UIAlertController,

    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.showMessageNew(msg: "hi", title: "hi")
                }
            }
    
        func showMessageNew(msg:String,title: String){
            let alertController = UIAlertController(title: title, message: msg, preferredStyle: .alert)
            let okAction = UIAlertAction(title: "OK", style: .default)
            alertController.addAction(okAction)
            self.present(alertController, animated: true)
        }
    }