monekypox121 monekypox121 - 1 month ago 12
iOS Question

how to present UIAlertController located in another UIViewController

I am getting the following error:


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


SplashViewController:

let check5ghz = Check5GHz()
check5ghz.determineIf5GHz()


Here is what Check5GHz looks like:

class Check5GHz: UIViewController {

func determineIf5GHz()-> Void{

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}


So it seems like the problem is that one ViewController is trying to launch an UIAlertController found in another ViewController which it does not seem to allow. But I need to have this UIAlertController appear from many different ViewControllers. Could you recommend another way?

Answer Source
extension UIViewController {
    func determineIf5GHz()-> Void{
        let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Click", style: 
        UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
}

Then in any of your view controllers do this:

self.determmineIf4GHz()