I have trouble to display my UIAlertController because I'm trying to show it in a Class which is not an ViewController.
I already tried adding it:
var alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
Which is not working... I didn't find any solution that worked for me yet.
Create a helper function that you call from the current view controller and pass the current view controller as a parameter:
If you solution is not working it probably because of there is no window at that moment. I had the same problem when I was trying to show alert view in
application:DidFinishLoadingWithOptions
method. In this case my solution was to check if root view controller is available, and if it's not, then add notification forUIApplicationDidBecomeActiveNotification
I wrote this
extension
overUIAlertController
to bring backshow()
.It uses recursion to find the current top view controller:
Now it's as easy as:
EDIT:
For Xcode 8.0 & Swift 3:
This should work.