【问题标题】:MFMailComposeViewController view does not dismiss 2nd timeMFMailComposeViewController 视图不会第二次关闭
【发布时间】:2017-03-30 21:28:40
【问题描述】:

我认为这是一个独特的问题。我无法关闭我的电子邮件窗口。我正在使用 Xcode 8。

电子邮件在我第一次打开时会正确关闭,但如果我再次打开它就不会。如果我按“取消”,它不会给我“删除草稿”的选项。如果我按“发送”,则会发送电子邮件,但窗口不会关闭。

我的代码如下。 mailComposeController 第一次被正确调用,但它永远不会被第二次调用。有人对我缺少什么有任何想法吗?

let mail = MFMailComposeViewController()
func sendEmail(body: String, subject: String) {
    if MFMailComposeViewController.canSendMail() {
        mail.mailComposeDelegate = self

        mail.setSubject(subject)
        mail.setMessageBody("\(body)", isHTML: false)

        if let data = (body as NSString).data(using: String.Encoding.utf8.rawValue){
            //Attach File
            mail.addAttachmentData(data, mimeType: "text/plain", fileName: "data.txt")
        }

        present(mail, animated: true)
    } else {
        // show failure alert
    }
}

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    controller.dismiss(animated: true, completion: nil)
}

【问题讨论】:

    标签: ios swift email messageui


    【解决方案1】:

    您每次都需要创建一个新的MFMailComposeViewController。将您的 mail 声明移动到 sendEmail 中可以工作...

    func sendEmail(body: String, subject: String) {
        if MFMailComposeViewController.canSendMail() {
    
           // Create a new MFMailComposeViewController…
           let mail = MFMailComposeViewController()
    
            mail.mailComposeDelegate = self
    
            mail.setSubject(subject)
            mail.setMessageBody("\(body)", isHTML: false)
    
            if let data = (body as NSString).data(using: String.Encoding.utf8.rawValue){
                //Attach File
                mail.addAttachmentData(data, mimeType: "text/plain", fileName: "data.txt")
            }
    
            present(mail, animated: true)
        } else {
            // show failure alert
        }
    }
    

    至于为什么……?

    【讨论】:

    • 与原始问题无关,但您可以在使用 utf8 字符串时从字符串中获取数据,而无需解包。 mail.addAttachmentData(Data(body.utf8), mimeType: "text/plain", fileName: "data.txt")
    • 感谢@LeoDabus 提出的代码改进建议。这也很有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多