MFMailComposeViewController 不发送电子邮件或关闭

MFMailComposeViewController does not send email or dismiss

我在视图控制器中使用 MFMailComposeViewController,代码如下:

if !MFMailComposeViewController.canSendMail() {
    return
}
let mailComposeViewController = MFMailComposeViewController()
mailComposeViewController.mailComposeDelegate = self
present(mailComposeViewController, animated: true)

并且:

extension MyViewController : MFMailComposeViewControllerDelegate {
    private func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true, completion: nil)
    }
}

MFMailComposeViewController 按预期显示,但具有以下行为:

这是Xcode11.2,iOS13.2,Swift4.

我该如何解决这个问题?

在此代码中

extension MyViewController : MFMailComposeViewControllerDelegate {
    private func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true, completion: nil)
    }
}

删除关键字private。它隐藏了 Cocoa 的方法,因此它永远不会被调用。

确保您的 class MyViewController 不是 MFMailComposeViewController 的子class。

你应该:

  1. 创建一个 UIViewController 子class(class MailViewController: UIViewController)
  2. 添加 MFMailComposeViewController。
  3. MailViewController: MFMailComposeViewControllerDelegate

或者:

直接从另一个 UIViewController 配置 MFMailComposeViewController()。例如:

let mailComposeVC = MFMailComposeViewController()
mailComposeVC.mailComposeDelegate = self
mailComposeVC.setToRecipients([recipient])
mailComposeVC.setSubject(subject)
mailComposeVC.setMessageBody(body, isHTML: false)
present(mailComposeVC, animated: true, completion: nil)