I have two view controllers: VC1 and VC2. From VC1, press a button will navigate app to VC2. VC2 has a network request function in viewDidLoad() which shows an alert if the request is failed.
If everything is fine, no request failure on VC2, when I move back to VC1, it would call to deinit function of VC2.
However, if the request failed and an error alert is shown, the deinit function (of VC2) wouldn't be called when I move back VC1. Moreover, it causes an error of "Presenting view controllers on detached view controllers is discouraged" while it's trying to show that alert after the screen displays VC1, screen then turns black except for navigation bar and the error alert of VC2 is shown on VC1 (The reason is when the VC2 is going to present the error alert, user suddenly press the back button on navigation bar to move back to previous screen). My alert is a global variable.
Here is the code I handle request and show alert on VC2:
func sendRegisterRequest() {
registerAPI.request(parameters: parameters) {
[weak self] (response) in
if let strongSelf = self {
strongSelf.handleResponse(response)
}
}
}
func handleResponse(response: Response<AnyObject, NSError>) {
let result = ResponseHandler.responseHandling(response)
if result.messageCode != MessageCode.Success {
// Show alert
handleResponseError(LocalizedStrings.registerFailedTitle, message: result.messageInfo, requestType: .Register)
return
}
}
func handleResponseError(title: String, message: String?, requestType: RequestType?) {
alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let action = UIAlertAction(title: LocalizedStrings.okButton, style: UIAlertActionStyle.Default) { (action) -> Void in
self.handleAlertViewAction(requestType)
}
alert.addAction(action)
dispatch_async(dispatch_get_main_queue(), {
self.presentViewController(self.alert, animated: true, completion: nil)
})
}
I attach the screenshot here:
Could anyone have solution for this issue? Any help could be appreciated,
Lucy Nguyen.
