Sending SMS messages in Swift is very easy. You can add the capability to any app with a few lines of code.
Note: This will not work in the simulator, as the simulator doesn’t support SMS messages!
Step 1: Import MessageIU
Add the following to the top of your ViewController.
import MessageUI
Step 2: Add the Protocol
Add the MFMessageComposeViewControllerDelegate your ViewController definition.
Step 3: Conform to the protocol
Conform to the MFMessageComposeControllerDelegate by adding defining the:
messageComposeViewController:didFinishWithResult method. It might look something like:
func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) {
switch result.rawValue {
case MessageComposeResultCancelled.rawValue :
print("message canceled")
case MessageComposeResultFailed.rawValue :
print("message failed")
case MessageComposeResultSent.rawValue :
print("message sent")
default:
break
}
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
You can omit the switch statement. The switch statement provides some feedback to you on the status of the message. Use this to notify your user when a message fails, or is canceled. Or omit if this is unimportant.
Step 3: Open the Message View controller
func sendMessage() {
let messageVC = MFMessageComposeViewController()
messageVC.body = "Message string"
messageVC.recipients = [] // Optionally add some tel numbers
messageVC.messageComposeDelegate = self
// Open the SMS View controller
presentViewController(messageVC, animated: true, completion: nil)
}
https://gist.github.com/1c863ab275e1c0e09936.git