Website Links

Tuesday 22 December 2015

Swift - Sending Emails and SMS from app

Opening up a pre-populated message composer in iOS which can be used to send an email or SMS is surprisingly easy. There is however, some issues you may encounter when testing this on a simulator where it lags and then crashes. So it is best to have a physical device available if you plan on testing this. I have also heard that having a singleton instance of your composer and showing this when required can help alleviate these issues. However, I needed to be able to send SMS/Emails based on a push notification, and on a physical device I didn't encounter these issues. Here's how I did it:

  import UIKit
  import MessageUI

  class MessageComposerViewController : UIViewController, 
    MFMailComposeViewControllerDelegate, 
    MFMessageComposeViewControllerDelegate {
    
    ...
    
    func sendEmail() {
      let emailVc = MFMailComposeViewController()
      emailVc.mailComposeDelegate = self
      emailVc.setSubject("Seasons Greetings!")
      emailVc.setMessageBody("<b>Merry Christmas!<br/>
        From Trip Wire</b>", isHTML: true)
      emailVc.setToRecipients(["hello@world.christmas"])
      presentViewController(emailVc, animated: true, 
        completion: nil)
    }

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

    func sendSms() {
      let smsVc = MFMessageComposeViewController()
      smsVc.body = "Seasons greetings! From the Trip Wire team";
      smsVc.recipients = ["5556789"]
      smsVc.messageComposeDelegate = self;
      presentViewController(smsVc, animated: true, 
        completion: nil)
    }

    func messageComposeViewController(
      controller: MFMessageComposeViewController, 
      didFinishWithResult result: MessageComposeResult) {
      dismissViewControllerAnimated(true, completion: nil)
    }

    ...

  }

No comments:

Post a Comment