MFMailComposeViewController view does not dismiss 2nd time

♀尐吖头ヾ 提交于 2019-12-01 06:06:28

问题


I have what I believe is a unique problem. I am having trouble getting my email window to dismiss. I am using Xcode 8.

The email dismisses correctly the first time I open it, but if I open it again it won't. If I press "Cancel" it does not give me the option to "Delete Draft". If I press "Send" the email is sent, but the window does not dismiss.

My code is below. The mailComposeController gets called correctly the first time, but it never gets called a second time. Does anyone have any ideas about what I am missing?

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:


You need to create a new MFMailComposeViewController each time. Moving your mail declaration inside sendEmail works…

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
    }
}

As to why…?



来源:https://stackoverflow.com/questions/43128688/mfmailcomposeviewcontroller-view-does-not-dismiss-2nd-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!