MFMailComposer Crashes on iOS 8 using Swift

1.1k views Asked by At

Here is a link to a simple app with same issue: https://drive.google.com/folderview?id=0B1t60Ehs8m62Wjl3QXl1YjY4TmM&usp=sharing

Here is the zip file on my server: http://xbsjason.com/test/DemoMessageUI.zip

Had to post on Google Drive as Dropbox required me to enter certain email addresses to view/edit.

I am having a problem with this piece of code for sending mail. When the user presses the mail button (form filled or not) after about 10 seconds the app crashes. In the simulator I can see that it has something to do with this code but I'm not sure what the problem is as I have nearly identical code running in another app with no issues. Can anyone spot an error here?

FYI I looked at related questions but none seem to address my error/crash. Thanks.

/* MAIL Sharing ====================================================*/
@IBAction func mailButt(sender: AnyObject) {
    var subjectText = "Glass Quote Request"
    var name = nameInput.text
    var phone = phoneNumber.text
    var year = carYear.text
    var make = carMake.text
    var model = carModel.text
    var glass = glassNeeded.text
    var messageText = "Please process quote for glass:<p>Respond to <b>\(name)</b> at     <b>\(phone)</b>. <p>The following glass is required: <p>Glass type: <b>\(glass)</b><p>For the following car:<p><b>\(year) \(make) \(model)</b> "

    var mailComposer: MFMailComposeViewController = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self
    mailComposer.setSubject(subjectText)
    mailComposer.setMessageBody(messageText, isHTML: true)
    mailComposer.setToRecipients(["[email protected]"])

    self.presentViewController(mailComposer, animated: true, completion: nil)
}
// Email results ================
func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) {
    switch result.value {
    case MFMailComposeResultCancelled.value:
        NSLog("Mail cancelled")
    case MFMailComposeResultSaved.value:
        NSLog("Mail saved")
    case MFMailComposeResultSent.value:
        NSLog("Mail sent")
    case MFMailComposeResultFailed.value:
        NSLog("Mail sent failure: %@", [error.localizedDescription])
    default:
        break
    }
    self.dismissViewControllerAnimated(false, completion: nil)
}
2

There are 2 answers

2
David H On

var mailComposer: MFMailComposeViewController is your problem. You need to keep a strong reference to this until its completely finished - use an ivar to hold it.

1
EricS On

Try checking +canSendMail before running that code. If you haven't set up a mail account on the device, your app will crash.

Looking a bit deeper, it looks there are also specific issues with MFMailComposeViewController similar to what David H said. See I have REAL misunderstanding with MFMailComposeViewController in Swift (iOS8) in Simulator