Dismissing modal view controller after sending email with MFMailComposeViewController

384 Views Asked by At

I have a view controller presented modally to let people sign up for a newsletter that then calls MFMailComposer. Once the mail is sent, I want to be able to dismiss the modal view controller after I click Send on the email window. Is this possible?

This was incorrectly marked a duplicate because my code is structured as follows:

CustomViewController calls ModalViewController ModalViewController calls MailComposer After user clicks send the ModalViewController needs to be dismissed.

1

There are 1 best solutions below

6
Tamás Sengel On

You should dismiss the controller in mailComposeController(_:didFinishWith:error:) after you checked that the MFMailComposeResult is sent.

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

    if result == .sent {
        dismiss(animated: true)
    }
}

Remember that you should set the delegate of the mail compose view controller and your view controller should conform to the MFMailComposeViewControllerDelegate protocol:

class CustomViewController: UIViewController, MFMailComposeViewControllerDelegate {
    fileprivate var mailComposeVc: MFMailComposeViewController!
    [...]

    func someFunc() {
        mailComposeVc.delegate = self
    }
}