Now UIAlertContoller can only be called with ViewController And this causes some inconvenience. Suppose the response from the server, and they are usually a separate file NSObject , you need to display an error. I would like to process the error right after the server responds to ``

I would like to find a way to run UIAlertContoller from any file in the program.

  • and what is it and what does nsobject have to do with it? - Max Mikheyenko
  • one
    I understand that the author decided to share his decision on a question that had tormented him for a long time. In this case, it would be better to formulate the question normally and answer it yourself, and insert the code with the decision into this answer. - Olter

1 answer 1

 func alert(title: String? = nil, message: String? = nil) { let alertController = UIAlertController(title: title, message:message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) let window = UIWindow(frame: UIScreen.mainScreen().bounds) window.rootViewController = UIViewController() window.makeKeyAndVisible() //The makeKeyAndVisible message makes a window key, and moves it to be in front of any other windows on its level window.rootViewController?.presentViewController(alertController, animated: true, completion: nil) } 

This code will trigger an Alert from anywhere in the program.