问题
I am trying to make an in-app popup alert using swift and I have run into an error that I know nothing about.
Here is the code I use to present my alert:
let welcomeAlert = UIAlertController(title: "Welcome!", message: “message here”, preferredStyle: UIAlertControllerStyle.Alert)
welcomeAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(welcomeAlert, animated: true, completion: nil)
println("welcome alert displayed!")
The error I'm getting back says this:
Warning: Attempt to present <UIAlertController: 0x7b89a950> on <MyApp.RootClientViewController: 0x7aea8fb0> whose view is not in the window hierarchy!
This is immediately followed by a printed statements stating welcome alert displayed!
.
So my code is certainly running, but for some reason, it won't display the alert...
What am I doing wrong?
回答1:
The error message tells you the answer: "view is not in the window hierarchy!" means self.view
is not on screen when the call is made (technically it means UIApplication.sharedApplication().keyWindow
is not an ancestor of self.view
).
Usually this happens when presenting a view controller in viewDidLoad()
or viewWillAppear(animated: Bool)
. Wait for viewDidAppear(animated: Bool)
, present from UIApplication.sharedApplication().delegate.window.rootViewController
or present from UIApplication.sharedApplication().keyWindow.rootViewController
.
来源:https://stackoverflow.com/questions/27197677/uialertcontroller-code-runs-but-doesnt-present-an-alert