我创建了一个用于发送邮件和短信的实用程序类。这是完整的代码。
class Utility: NSObject, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate
{
var subject: String!
var body: String!
var to: [String]!
var cc: [String]!
var viewController: UIViewController!
// MARK: Email utility
/// sendEmail : Sends email
///
/// - Parameters:
/// - vc: UIViewController from which mail is to be sent
/// - subj: Email subject
/// - emailBody: Email body
/// - toRecipients: To recipients
/// - ccRecipients: CC recipients
func sendEmail(vc: UIViewController, subj: String, emailBody: String, toRecipients: [String], ccRecipients: [String])
{
self.subject = subj
self.body = emailBody
self.to = toRecipients
self.cc = ccRecipients
self.viewController = vc
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.viewController.present(mailComposeViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert()
}
}
/// Show error alert when email could not be sent
func showSendMailErrorAlert() {
let alert = 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)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.viewController.present(alert, animated: true, completion: nil)
}
/// configuredMailComposeViewController : Set up mail compose view controller
///
/// - Returns: <#return value description#>
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(self.to)
mailComposerVC.setCcRecipients(self.cc)
mailComposerVC.setSubject(self.subject)
mailComposerVC.setMessageBody(self.body, isHTML: false)
return mailComposerVC
}
// MARK: MFMailComposeViewControllerDelegate
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
// MARK: END
// MARK: SMS utility
func sendSMS(vc: UIViewController, content: String, phoneNumber: String)
{
self.viewController = vc
if (MFMessageComposeViewController.canSendText()) {
let messageController = MFMessageComposeViewController()
messageController.body = content
messageController.recipients = [phoneNumber]
messageController.messageComposeDelegate = self
self.viewController.present(messageController, animated: true, completion: nil)
}
}
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
//... handle sms screen actions
controller.dismiss(animated: true, completion: nil)
}
// MARK: END
两个功能上的取消按钮都会崩溃。事实上,如果我在didFinishWith
上为这两个功能设置断点,则不会调用该函数并在此之前出现崩溃。
奇怪的是,如果我在UIViewController类中编写此代码,它可以正常工作。