I've just created a Single View Application project with ViewController class. I would like to show a UIAlertController from a function which is located inside my own class.
Here is my class with an alert.
class AlertController: UIViewController {
func showAlert() {
var alert = UIAlertController(title: "abc", message: "def", preferredStyle: .Alert)
self.presentViewController(alert, animated: true, completion: nil)
}
}
Here is ViewController which executes the alert.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func showAlertButton(sender: AnyObject) {
var alert = AlertController()
alert.showAlert()
}
}
This is what I get instead of beautiful alert.
Warning: Attempt to present UIAlertController: 0x797d2d20 on Sprint1.AlertController: 0x797cc500 whose view is not in the window hierarchy!
What should I do?
Let's look at your view hierarchy. You have a
ViewController
. Then you are creating anAlertController
, you are not adding it to your hierarchy and you are calling an instance method on it, that attempts to use theAlertController
as presenting controller to show just another controller (UIAlertController
).To simplify your code
This will work.
If you need the
AlertController
for something, you will have to add it to the hierarchy first, e.g. usingaddChildViewController
or using anotherpresentViewController
call.If you want the class to be just a helper for creating alert, it should look like this:
called as
It helped me to stick a slight delay between the viewDidLoad method and firing the alert method:
Write the following 3 lines, all we need to do is this.
Swift 3.0
Swift 2.0
Here is the code of an UIAlertController in a Utility.swift class (not a UIViewController) in Swift3, Thanks Mitsuaki!
If you're instancing your
UIAlertController
from a modal controller, you need to do it inviewDidAppear
, not inviewDidLoad
or you'll get an error.Here's my code (Swift 4):
You can use below function to call alert from any where just include these method in AnyClass
Then call