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)
}
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…?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With