MFMailComposeViewControllerDelegate没有在其他类别的Swift中被调用4

时间:2018-08-16 16:25:53

标签: swift messageui

我有这段代码,关于didFinishWith结果的问题未调用,应用程序崩溃。这是我的代码

注意:在目标C中,此代码可以正常工作,因为我在类中创建了强大的引用,但是我在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)
    }
}

在其他班级,我有下面的代码显示电子邮件:

@IBAction func sendEmail(_ sender: UIButton) {

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

1 个答案:

答案 0 :(得分:2)

它崩溃是因为您有EmailCreatorMFMailComposeViewControllerfunc createMailComposeViewController的本地变量。到MFMailComposeViewController调用didFinishWith方法时,EmailCreator已被deinit编辑。 您可以通过使您的EmailCreator实例成为强属性来解决此问题。

YourViewController: UIViewController {
    let email = EmailCreator()

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