How do I close the MFMailComposeViewController?

I want to send an email from my Swift app and it works well, it sends an email.

However, the layout does not complete after sending the email. I want to exit layout after sending an email. I also want this behavior when I click the Cancel, Delete Draft, or Save Draft button.

This is the code I need to email (after clicking the button):

@IBAction func btnSendEmailAction(_ sender: AnyObject) {

    let composeVC = MFMailComposeViewController()
    composeVC.mailComposeDelegate = self

    composeVC.setToRecipients(["mymail@mail.com"])
    composeVC.setSubject("Hello!")
    composeVC.setMessageBody("Hello World!", isHTML: false)

    self.present(composeVC, animated: true, completion: nil)
}

func mailComposeController(controller: MFMailComposeViewController,
                           didFinishWithResult result: MFMailComposeResult, error: NSError?) {

    switch result {

    case MFMailComposeResult.cancelled:
        controller.dismiss(animated: true, completion: nil)
        break

    case MFMailComposeResult.sent:
        controller.dismiss(animated: true, completion: nil)
        break

    case MFMailComposeResult.failed:
        controller.dismiss(animated: true, completion: nil)
        break

    default:
        break
    }

    controller.dismiss(animated: true, completion: nil)
}

      

but the layout doesn't complete when I click the Cancel or Submit buttons.

I know there are many questions related to this issue, but I've looked at them a lot and this is the code I could get from several of them. Note that most of them are in Objective instead of Swift (and sometimes methods don't exist).

Example: iPhone: How to close MFMailComposeViewController?

Am I missing something in my code? How can I define "Delete Draft" and "Save Draft"?

Thanks in advance!

+2


source to share


1 answer


It looks like you are using swift 3 and not using a valid delegate method. Fixed delegation method:



func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {

        switch result {
        case .cancelled:
            break
        case .saved:
            break
        case .sent:
            break
        case .failed:
            break

        }

        controller.dismiss(animated: true, completion: nil)
    }

      

+5


source







All Articles