how to dismiss mail view controller after tapping send or cancel button

is had an Switch Statement that controls it for me:

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

    switch result.rawValue {
    case MFMailComposeResult.cancelled.rawValue :
        print("Cancelled")

    case MFMailComposeResult.failed.rawValue :
        print("Failed")

    case MFMailComposeResult.saved.rawValue :
        print("Saved")

    case MFMailComposeResult.sent.rawValue :
        print("Sent")



    default: break


    }

    self.dismiss(animated: true, completion: nil)

}

Swift 4.0 Update. Swift 5.0 Update.

Allow me to add something to the discussion...

In Swift 4 and 5 the delegate method slightly changed; As it's posted by you now, won't do any effect and won't get called. It happened to me, drove me crazy!

The Xcode warning suggest three fixes but first two could be misleading. It's just a tiny fix...

Here's the delegate method fixed for Swift 3, 4 and 5:

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

        // Dismiss the mail compose view controller.
        controller.dismiss(animated: true, completion: nil)
    }

Still, Victor's answer should be the correct/accepted one.

Enjoy!


I think @rmaddy answer your question in his comment, nevertheless I going to explain you what's happening. You're trying to dismiss the UIViewController that presents the MFMailComposeViewController not the MFMailComposeViewController.

As Apple specify in his documentation:

The mail compose view controller is not dismissed automatically. When the user taps the buttons to send the email or cancel the interface, the mail compose view controller calls the mailComposeController:didFinishWithResult:error: method of its delegate. Your implementation of that method must dismiss the view controller explicitly.

So you need to set the method in this way:

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

    // Dismiss the mail compose view controller.
    controller.dismissViewControllerAnimated(true, completion: nil)
}

I hope this help you.