John
John

Reputation: 1888

Sending an email from an app using MFMail

I'm trying to make my app able to access and send an email after a button is pressed. This is what I have so far and when I run it, and click the help button the alert pops up and the cancel button works fine but the email part of the alert crashes the app. When it crashes it highlights the class AppDelegate: UIResponder, UIApplicationDelegate line and says Thread 1: signal SIGABRT.

@IBAction func helpButtonAction(sender: UIButton) {
        let alert = UIAlertController(title: "Help", message: "Click 'Email' to email support", preferredStyle: UIAlertControllerStyle.Alert)

    alert.addAction(UIAlertAction(title: "Email", style: UIAlertActionStyle.Default, handler: { action in
        let emailTitle = "Help Request"
        let messageBody = ""
        let toRecipents = ["[email protected]"]
        let mc: MFMailComposeViewController = MFMailComposeViewController()
        mc.mailComposeDelegate = self
        mc.setSubject(emailTitle)
        mc.setMessageBody(messageBody, isHTML: false)
        mc.setToRecipients(toRecipents)

        self.presentViewController(mc, animated: true, completion: nil)
    }))

    alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    self.dismissViewControllerAnimated(false, completion: nil)
}

Heres the console error...

    'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target <app.ViewController: 0x13c64a5f0>.'
*** First throw call stack:
(0x183930f48 0x19847ff80 0x18923def4 0x189240800 0x188fbdea0 0x10004909c 0x1000491d0 0x100048cbc 0x100048d0c 0x1893297d8 0x189329f70 0x189218ba4 0x18921bd9c 0x188ff3668 0x188eff240 0x188efed3c 0x188efebc4 0x1886c5c2c 0x1013d5c68 0x1013db710 0x1838e81f8 0x1838e6060 0x183814ca0 0x18e87c088 0x188f2cffc 0x10004ee78 0x198cc28b8)
libc++abi.dylib: terminating with uncaught exception of type NSException

Upvotes: 0

Views: 156

Answers (1)

Ulysses
Ulysses

Reputation: 2317

The problem is how you are instantiating a View Controller.

This code will instantiate the class, but not the view as you want to.

let mc: MFMailComposeViewController = MFMailComposeViewController()

The proper way to do so, can be found in the link above, i will just copy the code here.

You must set an identifier to your view controller, instantiating it by the storyboard, and then, presenting it.

let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("someViewController") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)

Instantiate and Present a viewController in Swift

Upvotes: 1

Related Questions