Sending SMS in iOS with Swift
Not sure if you really got the answer. I was in a similar hunt and came across this solution and got it to work.
import UIKitimport MessageUIclass ViewController: UIViewController, MFMessageComposeViewControllerDelegate { @IBOutlet weak var phoneNumber: UITextField! override func viewDidLoad() { super.viewDidLoad() } @IBAction func sendText(sender: UIButton) { if (MFMessageComposeViewController.canSendText()) { let controller = MFMessageComposeViewController() controller.body = "Message Body" controller.recipients = [phoneNumber.text] controller.messageComposeDelegate = self self.presentViewController(controller, animated: true, completion: nil) } } func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) { //... handle sms screen actions self.dismissViewControllerAnimated(true, completion: nil) } override func viewWillDisappear(animated: Bool) { self.navigationController?.navigationBarHidden = false }}
Swift 3.0 Solution:
func sendSMSText(phoneNumber: String) { if (MFMessageComposeViewController.canSendText()) { let controller = MFMessageComposeViewController() controller.body = "" controller.recipients = [phoneNumber] controller.messageComposeDelegate = self self.present(controller, animated: true, completion: nil) } } func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { //... handle sms screen actions self.dismiss(animated: true, completion: nil) } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.isNavigationBarHidden = false }
For sending iMessage in Swift 5 I use following code
Just MessageUI package and implement MFMessageComposeViewControllerDelegate
import UIKitimport MessageUIclass ViewController: UIViewController, MFMessageComposeViewControllerDelegate { override func viewDidLoad() { super.viewDidLoad() } @IBAction func sendNewIMessage(_ sender: Any) { let messageVC = MFMessageComposeViewController() messageVC.body = "Enter a message details here"; messageVC.recipients = ["recipients_number_here"] messageVC.messageComposeDelegate = self self.present(messageVC, animated: true, completion: nil) } func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { switch (result) { case .cancelled: print("Message was cancelled") case .failed: print("Message failed") case .sent: print("Message was sent") default: return } dismiss(animated: true, completion: nil) }}