Peilin Li Peilin Li - 3 months ago 12
iOS Question

Failed on using Swift to implement in-app email

I want to use swift to implement in-app email. When I click the button, the email window pops up. However, I am unable to send my email. Moreover, after I click cancel-delete draft, I cannot go back to the original screen.

import UIkit
import MessageUI

class Information : UIViewController, MFMailComposeViewControllerDelegate{

var myMail: MFMailComposeViewController!

@IBAction func sendReport(sender : AnyObject) {

myMail = MFMailComposeViewController()


// set the subject
myMail.setSubject("My report")

//To recipients
var toRecipients = [""]

//CC recipients
var ccRecipients = [""]

//CC recipients
var bccRecipients = [""]

//Add some text to the message body
var sentfrom = "Email sent from my app"
myMail.setMessageBody(sentfrom, isHTML: true)

//Include an attachment
var image = UIImage(named: "Gimme.png")
var imageData = UIImageJPEGRepresentation(image, 1.0)

myMail.addAttachmentData(imageData, mimeType: "image/jped", fileName: "image")

//Display the view controller
self.presentViewController(myMail, animated: true, completion: nil)
var alert = UIAlertController(title: "Alert", message: "Your device cannot send emails", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)


func mailComposeController(controller: MFMailComposeViewController!,
didFinishWithResult result: MFMailComposeResult,
error: NSError!){

case MFMailComposeResultSent.value:
println("Email sent")


self.dismissViewControllerAnimated(true, completion: nil)



Since you haven't set the current view controller as the mailComposeDelegate of myMail, the mailComposeController:didFinishWithResult method isn't being called. After you init myMail, make sure to add:

myMail.mailComposeDelegate = self

and you'll be good to go