未在其他类swift 4中调用MFMailComposeViewControllerDelegate
我有这段代码,问题是没有调用didFinishWith结果,应用程序崩溃。这是我的密码 注意:在目标C中,此代码运行良好,因为我在类中创建了一个强引用,但我在Swift中遇到了一个问题,我不知道如何解决此问题未在其他类swift 4中调用MFMailComposeViewControllerDelegate,swift,messageui,Swift,Messageui,我有这段代码,问题是没有调用didFinishWith结果,应用程序崩溃。这是我的密码 注意:在目标C中,此代码运行良好,因为我在类中创建了一个强引用,但我在Swift中遇到了一个问题,我不知道如何解决此问题 import Foundation import MessageUI class EmailCreator: NSObject, MFMailComposeViewControllerDelegate { // in other class I send this var to
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()
}
它崩溃是因为您有
EmailCreator
,这是一个本地变量,是MFMailComposeViewController
的委托,如您的func createMailComposeViewController
中所示。当MFMailComposeViewController
调用didFinishWith
方法时,EmailCreator
已被deinit
ed。
您可以通过将您的EmailCreator
实例设置为强属性来解决此问题
YourViewController: UIViewController {
let email = EmailCreator()
@IBAction func sendEmail(_ sender: UIButton) {
email.viewToShow = self
email.sendEmail()
}
}
什么是崩溃和堆栈跟踪?线程1:EXC_BAD_ACCESS(代码=1,地址=0xb6f4ebeb8)编辑您的问题并将整个内容添加到那里。我不能用它来帮助你。当它崩溃时,控制台中有日志吗?还有,是什么导致了这次撞车?另外,您正在创建一个
UIViewController
来替换它,为什么不创建var viewthow:UIViewController?
?然后viewthow?.present(mailComposeViewController,动画:true,完成:nil)
我在cosole中没有日志。应用程序显示此错误:线程1:EXC_BAD_ACCESS(代码=1,地址=0xb6f4ebeb8)我还使用此代码改进了类EmailCreator:)中lazy var viewthow=MyvcthowMail()的行为,现在可以很好地工作了