Reputation: 23
Is there any possible way to perform an action after a segue has finished in swift?
I am calling this code:
self.performSegue(withIdentifier: "showDamageReportSegue", sender: self)
The segue opens a new ViewController modal and after the user presses the done button I want it to continue running the code underneath which is
self.performReservationEndingSequence() // which does some calls etc
Is there maybe a completion handler
for performSegue
that I am missing? I've been searching but I cannot find this specific question.
Upvotes: 0
Views: 2239
Reputation: 285132
A reasonable solution is a callback closure.
In the showDamageReportSegue controller add a callback property
var callback : (() -> Void)?
In the showDamageReportSegue controller call callback
in viewDidDisappear
override func viewDidDisappear(_ animated : Bool) {
super.viewDidDisappear(animated)
callback?()
}
or at any other arbitrary place.
In the first view controller implement prepare(for
and set the callback
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "showDamageReportSegue" else { return }
let destination = segue.destination as! ShowDamageReportController // change that to the real class
destination.callback = {
self.performReservationEndingSequence()
}
}
Upvotes: 4
Reputation: 1125
Write it in viewDidDisappear
event of the view controller.
override func viewDidDisappear(_ animated: Bool) {
super.viewDidAppear(animated)
print("ViewController Dismissed")
}
Edit: For some code to execute over a specific segue, use prepare delegate method with the triggering segue's identifier and it should execute whenever that segue is triggered:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SomeViewController" {
print("Segue triggered for SomeViewController")
}
}
Upvotes: 2
Reputation: 5223
There is a prepareForSegue method which is called before performSegue
, you can call your function there. and also check if segue.identifier == "yourIdentifier"
, then only call the function, else dont
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "yourSegueIdentifier" {
self.performReservationEndingSequence() // call the function
} else {
print("dont call the function")
}
}
Upvotes: 0