我有一个mailHelper类,如下所示:
class MailHelper: NSObject, MFMailComposeViewControllerDelegate {
//MARK: Mail Function
func configuredInquiryMailComposeViewController(rootViewController: UIViewController) {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont(name: "AvenirNext-Medium", size: 20)!]
mailComposerVC.navigationBar.tintColor = UIColor.whiteColor()
mailComposerVC.navigationBar.translucent = false
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["(email)"])
mailComposerVC.setSubject("(title)")
mailComposerVC.setMessageBody("[Please write your inquiries below. We will reply shortly]", isHTML: false)
if MFMailComposeViewController.canSendMail() {
rootViewController.presentViewController(mailComposerVC, animated: true, completion: nil)
} else {
showSendMailErrorAlert()
}
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertController(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction: UIAlertAction = UIAlertAction(title: "Ok", style: .Cancel, handler: nil)
sendMailErrorAlert.addAction(cancelAction)
self.presentViewController(sendMailErrorAlert, animated: true, completion: nil)
}
// MARK: MFMailComposeViewControllerDelegate Method
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
然后我在主视图控制器中调用这个辅助函数:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.section == 0 && indexPath.row == 0) {
let mailHelperClass = MailHelper()
mailHelperClass.configuredInquiryMailComposeViewController(self)
}
}
当我在主视图控制器中单击tableview中的单元格时,将成功显示Mail Composer。问题是每当我点击"发送"或"取消"邮件编辑器中的按钮,它会崩溃应用程序。
为了确定这个帮助程序类是否错误,我删除了帮助程序类,并将所有与邮件编辑器相关的函数迁移到我的主视图控制器中。然后,每当我点击"发送"或"取消"按钮。我在mail helper class
中做错了什么?
当它崩溃时,它不会给我任何错误信息。
答案 0 :(得分:4)
这里的问题不明显,但问题是MFMailComposeViewControllerDelegate
。当您使用自定义类呈现邮件编辑器时,您已将该类的对象指定为delegate
,并且未保留该对象。一旦MailHelper
的对象离开了它的范围,它就会被释放,当你试图发送或取消邮件编辑器时,它会向解除分配的对象发送消息,因为对象不再存在了应用程序崩溃了,那就是它!
此外,您应该在创建邮件编辑器的对象之前检查邮件编辑器canSendMail()
是否可以发送邮件,为什么要创建对象?
希望这有帮助!