MFMailComposeViewController视图不会第二次关闭

Rya*_*yer 3 email messageui ios swift

我有一个唯一的问题。我无法关闭电子邮件窗口。我正在使用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)
}
Run Code Online (Sandbox Code Playgroud)

Ash*_*lls 6

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
    }
}
Run Code Online (Sandbox Code Playgroud)

至于为什么……?

  • 与原始问题无关,但是在使用utf8字符串时,您可以从字符串获取数据而无需将其拆包。mail.addAttachmentData(Data(body.utf8),mimeType:“ text / plain”,fileName:“ data.txt”) (2认同)