MFMailComposeViewControllerDelegate 未在其他 class swift 4 中被调用

MFMailComposeViewControllerDelegate not being called in other class swift 4

我有这段代码,问题是它的 didFinishWith 结果没有被调用,应用程序崩溃了。这是我的代码

注意:在 Objective C 中,这段代码工作正常,因为我在 class 中创建了一个强引用,但我在 Swift 中遇到了问题,我不知道如何解决这个问题

import Foundation
import MessageUI

class EmailCreator: NSObject, MFMailComposeViewControllerDelegate {
    // in other class I send this var to show email
    var viewToShow = UIViewController ()

    func sendEmail() {

        let mailComposeViewController = createMailComposeViewController()
        if MFMailComposeViewController.canSendMail(){
            viewToShow.present(mailComposeViewController, animated: true, completion: nil)
        }else{
            print("Can't send email")
        }
    }

    func createMailComposeViewController() -> MFMailComposeViewController {
        let mailComposeViewController = MFMailComposeViewController()
        mailComposeViewController.mailComposeDelegate = self
        mailComposeViewController.setToRecipients(["example@test.test"])
        mailComposeViewController.setSubject("subject")
        mailComposeViewController.setMessageBody("test body", isHTML: false)
        return mailComposeViewController
    }
    //MARK: - MFMail compose method
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true, completion: nil)
    }
}

在其他 class 我有这个代码来显示电子邮件:

@IBAction func sendEmail(_ sender: UIButton) {

        let email = EmailCreator()
        email.viewToShow = self
        email.sendEmail()
}

它崩溃是因为你有 EmailCreator,一个本地变量 MFMailComposeViewController 的委托,如你的 func createMailComposeViewController 所示。在 MFMailComposeViewController 调用 didFinishWith 方法时,EmailCreator 已经 deinited。 您可以通过将 EmailCreator 实例设为强 属性.

来解决此问题
YourViewController: UIViewController {
    let email = EmailCreator()

     @IBAction func sendEmail(_ sender: UIButton) {
        email.viewToShow = self
        email.sendEmail()
    }
}