Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MFMailComposeViewController does not dismiss

I'm trying to implement MFMailComposeViewController in case of sending the emails from within my application. The problem is that after presenting MFMailComposeViewController it is not dismissing by "Cancel" or "Send" buttons, just a bit scrolls up.

Here is the presenting of it:

func mailButtonDidPressed {
        let emailTitle = "Test email"
        let messageBody = "some body bla bla bla"
        let toRecipents = "[email protected]"

        let emailComposer = MFMailComposeViewController()
        emailComposer.setSubject(emailTitle)
        emailComposer.setMessageBody(messageBody, isHTML: false)
        emailComposer.setToRecipients([toRecipents])
        emailComposer.mailComposeDelegate = self
        self.presentViewController(emailComposer, animated: true, completion: nil)
    }

and dismissing delegate code:

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    switch (result) {
    case MFMailComposeResultSent:
        print("You sent the email.")
        break
    case MFMailComposeResultSaved:
        print("You saved a draft of this email")
        break
    case MFMailComposeResultCancelled:
        print("You cancelled sending this email.")
        break
    case MFMailComposeResultFailed:
        print("Mail failed:  An error occurred when trying to compose this email")
        break
    default:
        print("An error occurred when trying to compose this email")
        break
    }

    controller.dismissViewControllerAnimated(true, completion: nil)
}

I have surfed through the StackOverflow and other services like this and could not find any answer.

like image 362
Pavel Zagorskyy Avatar asked Aug 09 '16 13:08

Pavel Zagorskyy


1 Answers

Swift 5

Remember to add both delegates:

emailComposer.mailComposeDelegate = self
emailComposer.delegate = self

If you only add one, it won't dismiss. Also make sure to implement the delegate method:

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    dismiss(animated: true)
}
like image 185
Ken Mueller Avatar answered Oct 14 '22 16:10

Ken Mueller