无法关闭邮件视图控制器

Can't dismiss mail view controller

此代码有效并显示所有填写的电子邮件表单并发送电子邮件,只是在发送或尝试取消后无法将其关闭。

我确信我遗漏了一些简单的东西。 我也意识到如果出现错误我什么都没有,但此时它可以工作并发送电子邮件但我无法将其关闭

尝试了我在网上找到的一些建议,还有其他方法可以做到这一点,但我试图理解为什么这不起作用所以希望这种方式(或关闭)起作用.... xcode 10.2 .1

import UIKit
import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func sendEmail(_ sender: Any) {

        sendEmail()

        }

    func sendEmail() {
        if MFMailComposeViewController.canSendMail() {
            let mail = MFMailComposeViewController()
            mail.mailComposeDelegate = self
            mail.setToRecipients(["xxx@xx.com"])
            mail.setSubject("test  ")
            mail.setPreferredSendingEmailAddress("xxx@jxxx.com")

            present(mail, animated: true)   

        } else {
            //show failure alert
        }

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

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

        }

    }

可以正常编译和发送电子邮件,只是无法关闭控制器

所有委托方法都应在 class 范围内,在您当前的代码 didFinishWith 中,应该将邮件嵌套在 sendEmail

import UIKit
import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func sendEmail(_ sender: Any) { 
        sendEmail() 
    }

    func sendEmail() {
        if MFMailComposeViewController.canSendMail() {
            let mail = MFMailComposeViewController()
            mail.mailComposeDelegate = self
            mail.setToRecipients(["xxx@xx.com"])
            mail.setSubject("test  ")
            mail.setPreferredSendingEmailAddress("xxx@jxxx.com") 
            present(mail, animated: true)   

        } else {
            //show failure alert
        } 
    }

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