How to close MFMailComposeViewController?

瘦欲@ 提交于 2019-12-23 22:20:02

问题


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

Nevertheless, after sending the email, the layout does not quits. I want to quit the layout after sending the email. I also want this behaviour when I press on Cancel, Remove draft or Save draft button.

This is the code that I have to send the email (after pressing a 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 does not quits when I press on Cancel or Sent buttons.

I know that there are a lot of questions related about this problem but I looked a lot of them and this is the code I could get from a mix of some of them. Note that most of them are in Objective instead of Swift (and sometimes the methods does not exist).

Example: iPhone: How to Close MFMailComposeViewController?

Am I missing something on my code? How can I detect Remove draft and Save Draft events?

Thanks in advance!


回答1:


Looks like you're using swift 3 and not using a valid delegate method. Corrected delegate method is this:

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

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

        }

        dismiss(animated: true, completion: nil)
    }


来源:https://stackoverflow.com/questions/40305421/how-to-close-mfmailcomposeviewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!