Search code examples
swiftmfmailcomposeviewcontroller

Why can't won't the MFMailComposerViewController be dismissed?


Whenever I press "Cancel" then "Delete Draft", the mail composer won't be dismissed. The error I'm getting is "Thread 1: EXC_BAD_ACCESS (code=1, address=0x40363380)"

In my TableViewController I have:

@IBAction func mailButton(sender: AnyObject) {
    let emailComposer = EmailComposer()
    if email != "" {
        print(email)
        if emailComposer.canSendMail() {
            emailComposer.setRecipient(email)
            let configuredMailComposeViewController = emailComposer.configuredMailComposeViewController()
            presentViewController(configuredMailComposeViewController, animated: true, completion: nil)
        }
    } else {
        let alertController = UIAlertController(title: "Sorry!", message: "No email found for this contact", preferredStyle: .Alert)
        alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
            //do nothing
        }))
         self.presentViewController(alertController, animated: true, completion:nil)
    }

}

Solution

  • For those who don't know, EXC_BAD_ACCESS means its trying to access something in memory that is no longer there. I wrongfully created the EmailComposer() object after the button tap so it was going out of scope. So this:

    let emailComposer = EmailComposer()
    

    ...should have been created here, for example:

    class TableViewController: UITableViewController {
    
    let emailComposer = EmailComposer()