Marcus Houpt
Marcus Houpt

Reputation: 11

Dismissing modal view controller after sending email with MFMailComposeViewController

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.

Upvotes: 0

Views: 383

Answers (1)

glyvox
glyvox

Reputation: 58139

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
    }
}

Upvotes: 0

Related Questions