Reputation: 1801
I want to move to another view using performSegue
as below
self.performSegue(withIdentifier: "successRegistration", sender: nil)
and I want to show an alert in my destination view so I overrides prepare function as below
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "successRegistration" {
loginModel.alert(fromController: self)
print("working")
}
}
but the prepare function doesn't seem to work because working
is not printed to the console
I tried removing my prepare
function and change my performSegue
as below
self.performSegue(withIdentifier: "successRegistration", sender: self.loginModel.alert(fromController: self))
the above line did print the alert but it didn't take me to the other view.
How can I show the alert after segueing to the other view?
Upvotes: 2
Views: 754
Reputation: 380
Check this one:
self.performSegue(withIdentifier: "successRegistration", sender: self)
Upvotes: 0
Reputation: 66
Showing an alert on your destination view controller in prepare would result in:
"Attempt to present UIAlertController on SecondViewController whose view is not in the window hierarchy!"
To achieve what you would like you could simply add a variable in your second view controller class and default it to false
//In your second view controller
var shouldPresentAlertOnOpen: Bool = false
Then you could add the logic to show your alert in that view controller's viewWillAppear method like so:
//Still in your second view controller
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if shouldPresentAlertOnOpen {
//Present your alert here
let alert = UIAlertController(title: "My Alert", message: "My awesome message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
Now back to your first view controller you could update your prepare method to:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "successRegistration" {
let destinationVC = segue.destination as! SecondViewController
destinationVC.shouldPresentAlertOnOpen = true
}
}
note that SecondViewController should be updated to your second view controller class.
I'm pretty sure there are other ways you could do it, this is just my approach.
Upvotes: 4
Reputation: 11233
You may try like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "successRegistration" {
loginModel.alert(fromController: segue.destinationViewController)
print("working")
}
}
and perform segue like this:
self.performSegue(withIdentifier: "successRegistration", sender: self)
It would be even more good if you pass some value to destinationViewController and show alert on next screen based on this value you are trying to display. Passed value could be like shouldDisplayLoginAlertOnLoad
etc.
Upvotes: 0