Olyve
Olyve

Reputation: 731

View not dismissing after UIAlertAction taken

So I am using a UIAlertController with an Action Sheet style to display two options, one to cancel the action and another to delete the data. The buttons work fine and the delete button works and the Action Sheet dismisses. My problem is that the view itself does not dismiss after the data is deleted from the cloud in the background. Why isn't the view dismissing itself?

@IBAction func deleteRecipePressed() {
// Create the alert controller
let actionSheetController: UIAlertController = UIAlertController(title: "Delete Recipe?", message: "Are you positive you want to delete this recipe? This action can not be undone!", preferredStyle: .ActionSheet)

// Create and add the cancel action
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {action -> Void in
  // Just dismiss the action sheet
})
actionSheetController.addAction(cancelAction)

// Create and add the delete action
let deleteAction: UIAlertAction = UIAlertAction(title: "Delete", style: .Default, handler: {action -> Void in
  // Set deleteRecipe to true to flag for deletion
  self.deleteRecipe = true
})
actionSheetController.addAction(deleteAction)

// Present the alert
self.presentViewController(actionSheetController, animated: true, completion: nil)

// If flagged for deletion, delete the recipe and dismiss the view
if (deleteRecipe == true) {
  recipeObject.deleteInBackground()
  self.dismissViewControllerAnimated(true, completion: nil)
}
}

Upvotes: 0

Views: 1240

Answers (1)

Paulw11
Paulw11

Reputation: 114975

This code -

// If flagged for deletion, delete the recipe and dismiss the view
if (deleteRecipe == true) {
  recipeObject.deleteInBackground()
  self.dismissViewControllerAnimated(true, completion: nil)
}

Executes immediately after the action sheet is shown. i.e. before the user has selected either option. self.presentViewController(actionSheetController, animated: true, completion: nil) does not block the current thread.

You need to delete your item and dismiss your view in the handler for the delete option -

let deleteAction: UIAlertAction = UIAlertAction(title: "Delete", style: .Default, handler: {action -> Void in
  recipeObject.deleteInBackground()
  self.dismissViewControllerAnimated(true, completion: nil)
})

Upvotes: 1

Related Questions