Calling UIAlertController outside of UIViewController

I've created a file called Functions.swift and inside that file I have a function called showAlert that (I want to) lets me open an alert from anywhere:


func showAlert(title: String, message: String, viewController: UIViewController) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    let dismissAction = UIAlertAction(title: "OK", style: .default) { (action) in
        // Action
    }
    alert.addAction(dismissAction)

    viewController.present(alert, animated: true, completion: nil)
}


I have a UIViewController called CreateAccount.swift and I'm trying to call showAlert but I'm getting an error:


Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may onlybe called from the main thread.'


And when I print out viewController it displays the correct UIViewController (CreateAccount) but it's not working like I'd expect.


Any ideas? Thanks!

It sounds like you are calling this function from a code that is not running on the main thread. You will need to present that viewcontroller on the main thread. That can be done this way:

//replace:
    viewController.present(alert, animated: true, completion: n

//with
dispatch_async(dispatch_get_main_queue(), ^{

    viewController.present(alert, animated: true, completion: nil)
});

Have you tried implementing this as an extension UIViewController. This the context will always be the current view controller on the main thread without the need for gcd.

Calling UIAlertController outside of UIViewController
 
 
Q