syedfa
syedfa

Reputation: 2809

Unable to present AlertController from a UIView in Swift

I am trying to display an AlertController in Swift, but not from a UIViewController, but from a UIView that is called from its parent UIViewController. When I try to call the controller, I am getting the following error:

Warning: Attempt to present <UIAlertController: 0x7fa5544a3140> on
<UINavigationController: 0x7fa553830400> whose view is not in the window
hierarchy!

The code that I have which is trying to call the alertController is this:

let logInButton = TWTRLogInButton { (session, error) in
            if let unwrappedSession = session {
                let alert = UIAlertController(title: "Logged In",
                    message: "User \(unwrappedSession.userName) has logged in",
                    preferredStyle: UIAlertControllerStyle.Alert
                )
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
                //self.presentViewController(alert, animated: true, completion: nil)
                UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
            } else {
                NSLog("Login error: %@", error!.localizedDescription);
            }
        }

The commented line in the above block of code is what the original block of code came with, and the line below the comment is the code I tried to replace it with. Can anyone see what it is I'm doing wrong?

Upvotes: 2

Views: 2896

Answers (3)

yassine menssi
yassine menssi

Reputation: 373

for swift 5 :

UIApplication.shared.keyWindow?.rootViewController?.presentedViewController?.present(alertName, animated: true, completion: nil)

Upvotes: 0

In Swift 5

let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first

window?.rootViewController?.presentedViewController?.present(alert, animated: true, completion: nil)

Upvotes: 0

Charles A.
Charles A.

Reputation: 11123

Is the root view controller already presenting a view controller? If so, you may need to use:

UIApplication.sharedApplication().keyWindow?.rootViewController?.presentedViewController?.presentViewController(alert, animated: true, completion: nil)

Having said that, it might be easier (and more consistent/appropriate) to use a delegate pattern and let the view tell whatever view controller is managing it to present the alert view controller.

Upvotes: 9

Related Questions