Tuesday, 11 November 2014

Swift + Send E-mail In-App using MFMailComposeViewController


In this writing, I want explore how to use MFMailComposeViewController with Swift to send e-mails within your app as a walkthrough.


First Add and Import MessageUI Framework.



import UIKit
import MessageUI



Second, we need to specify that the View Controller will conform to
the MFMailComposeViewControllerDelegate protocol.  Later, we’ll actually implement the method that this protocol outlines, which will allow us to make the email composer screen go away once the user is finished either sending an e-mail or cancels out of sending one.




@IBAction func sendEmailButtonTapped(sender: AnyObject)
{
        let mailComposeViewController = configuredMailComposeViewController()
       
        if MFMailComposeViewController.canSendMail()
        {
            self.presentViewController(mailComposeViewController, animated: true, completion: nil)
        }
        else
        {
            self.showSendMailErrorAlert()
        }
}








   func configuredMailComposeViewController() -> MFMailComposeViewController
    {
        let mailComposerVC = MFMailComposeViewController()
    
        mailComposerVC.mailComposeDelegate = self
        
        
        mailComposerVC.setToRecipients(["test@domain.com"])
        
        
        mailComposerVC.setSubject("Sending you an in-app e-mail...")
        
        
        mailComposerVC.setMessageBody("Sending e-mail in-app is not so bad!", isHTML: false)
        
        return mailComposerVC
        
    }
    
    
    
    
    
    func showSendMailErrorAlert()
    {
        
        
        let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail.  Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
        
        
        sendMailErrorAlert.show()
        
        
    }
    
    
    
    
    
    // MARK: MFMailComposeViewControllerDelegate Method
    
    
    func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!)
    {
        
        
        controller.dismissViewControllerAnimated(true, completion: nil)
        
        
    }

No comments:

Post a Comment