I try the next code snippet:
var alert = UIAlertController(title: "Alert", message: "Cannot connect to : \(error!.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
in my AppDelegate, but it prints me the next error in console:
Warning: Attempt to present <UIAlertController: 0x7ff6cd827a30> on <Messenger.WelcomeController: 0x7ff6cb51c940> whose view is not in the window hierarchy!
How can I fix this error?
@OrkhanAlizade create a ViewController , put your code into the ViewControllers viewDidAppear method, and in your AppDelegate , set that ViewController as the windows rootViewController (and also don't forget to create the window itself). @DánielNagy it works!
Adding Action Buttons to Alert Dialog To create an action button that the user can tap on, we will need to create a new instance of an UIAlertAction class and add it to our alert object. To add one more button to UIAlertController simply create a new UIAlertAction object and add it to the alert.
This is what i'm using now to do that.
var alertController = UIAlertController(title: "Title", message: "Any message", preferredStyle: .ActionSheet) var okAction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default) { UIAlertAction in NSLog("OK Pressed") } var cancelAction = UIAlertAction(title: "No", style: UIAlertActionStyle.Cancel) { UIAlertAction in NSLog("Cancel Pressed") } alertController.addAction(okAction) alertController.addAction(cancelAction) self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
Swift 5:
let alert = UIAlertController(title: "Test", message:"Message", preferredStyle: UIAlertController.Style.alert) // add an action (button) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)) // show the alert self.window?.rootViewController?.present(alert, animated: true, completion: nil)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With