我有这段代码,问题是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()
}发布于 2018-08-22 17:17:24
它崩溃是因为您有一个EmailCreator,一个本地变量MFMailComposeViewController的委托,如您的func createMailComposeViewController中所示。当MFMailComposeViewController调用didFinishWith方法时,EmailCreator已经被deinit编辑了。您可以通过使您的EmailCreator实例成为一个强属性来解决这个问题。
YourViewController: UIViewController {
let email = EmailCreator()
@IBAction func sendEmail(_ sender: UIButton) {
email.viewToShow = self
email.sendEmail()
}
}https://stackoverflow.com/questions/51881565
复制相似问题