Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show alert in AppDelegate in Swift [duplicate]

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?

like image 443
Orkhan Alizade Avatar asked Aug 24 '15 10:08

Orkhan Alizade


People also ask

How do I add an alert in AppDelegate Swift?

@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!

How do I present an alert in Swift?

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.


2 Answers

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) 
like image 103
Jorge L Hernandez Avatar answered Sep 19 '22 21:09

Jorge L Hernandez


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) 
like image 41
Ahmed Safadi Avatar answered Sep 16 '22 21:09

Ahmed Safadi