Lawrence413 Lawrence413 - 1 year ago 126
Swift Question

UIAlertController Gets Deallocated Before Presenting It

I want to make a "rate app" alert, but for some reason it gets deallocated before showing it.

Here's the code:

func showAlert() {
if #available(iOS 8.0, *)
let alertController = UIAlertController(title: "Rate App", message: "Rate this app now", preferredStyle: .Alert)
let neverAction = UIAlertAction(title: "Never Show This Again", style: .Destructive, handler: { (action: UIAlertAction) in
self.userDefaults.setBool(true, forKey: "rateAlertRejected")
let rateAction = UIAlertAction(title: "Rate Now", style: .Default, handler: { (action: UIAlertAction) in
// Rate App
let remindAction = UIAlertAction(title: "Remind Me Later", style: .Cancel, handler: nil)


presentViewController(alertController, animated: true, completion: nil)
// Identical code (using UIAlertView) for iOS 7 which works perfectly

The method executes (in certain conditions, but for testing purposes it does it every time) after a custom unwind segue.

Why do I have this problem? I used
before but I had no issues.

Answer Source

According to your comment you show showAlert in a method that executes after a custom unwind segue.

unwind segue dismisses the view heriarchy and therefore your alert does not get reference to a view controller to show from.

To solve this, show your alert in the View controller you unwind to or wait for the alert controller action to be completed before unwinding.