问题
I have two classes, ChargeCustomer and TwelvethViewController.
In TwelvethViewController I have a func goNextView() which should perform a segue to next view controller when called.
goNextView() is called from class ChargeCustomer inside a Alamofire completion handler.
The problem is that this function goNextView() is never called and I can't figure out why.
I tried to make it work based on this answer on stackoverflow Perform Segue From Another Swift File via a class function
class TwelvethViewController:UIViewController {
//when this func is called, it should segue to Thiretheen
func goNextView() {
performSegue(withIdentifier: "twelvethToThiretheen", sender: self)
}
}
class ChargeCustomer {
//send a post request to the server
Alamofire.request(urlString, method: .post, parameters: params, encoding: JSONEncoding.default, headers: ["Content-Type":"application/json"]).responseJSON {
(response: DataResponse<Any>) in
print("received reply from ALamofire") //prints string
//perform segue to Thireteen View Controller
func showNextView(fromViewController:TwelvethViewController) {
print("went through") //doesn't print
fromViewController.goNextView()
print("it has segued") //doesn't print
}
} ///end of Alamofire
} //end of chargeUsingCustomer
Updated answer according to José Neto
class ChargeCustomer {
//create instance of the viewcontroller that has segue with identifier twelvethToThiretheen
let twelvethVC = TwelvethViewController()
//send a post request to the server
Alamofire.request(urlString, method: .post, parameters: params, encoding: JSONEncoding.default, headers: ["Content-Type":"application/json"]).responseJSON {
(response: DataResponse<Any>) in
print("received reply from ALamofire") //prints string
//perform segue to Thirteen View Controller
//crashes: <CleaningApp.TwelvethViewController: 0x7fd4e16ad2a0>) has no
//segue with identifier 'twelvethToThiretheen''
self.showNextView(fromViewController: self.twelvethVC )
} //end of Alamofire
//perform segue to Thireteen View Controller
func showNextView(fromViewController:TwelvethViewController) {
fromViewController.goNextView()
}
} //end of chargeUsingCustomer
回答1:
You have to instantiated the storyBoard that you want then the TwelvethViewController and finally you can push. Like this:
let storyBoard = UIStoryboard(name: "youStoryBoard", bundle: nil)
let vc = storyboard?.instantiateViewController(withIdentifier: "youVCIndentifier") as! TwelvethViewController
self.navigationController?.pushViewController(vc, animated: true)
来源:https://stackoverflow.com/questions/42458405/perform-segue-from-another-class-with-helper-function