MFMailComposeViewController视图第二次不会消失

5
我有一个我认为很独特的问题。我在使用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)
}
1个回答

8
每次都需要创建一个新的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
    }
}

关于为什么...?

2
在处理UTF8字符串时,您可以直接从字符串中获取数据,而无需对其进行解包。mail.addAttachmentData(Data(body.utf8), mimeType: "text/plain", fileName: "data.txt") - Leo Dabus
1
同时感谢@LeoDabus提供的代码改进建议。那个也很好用。 - Ryan Tensmeyer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接