Search code examples
iosswift2mfmailcomposeviewcontroller

Send SMS Message to multiple recipients in Swift


I want to send a single message to multiple recipients using MFMessageComposeViewController, I am unable to add the second and so on recipients

here's my code :

@IBAction func sendSms(sender: AnyObject) {

        if (MFMessageComposeViewController.canSendText())
        {
            let controller = MFMessageComposeViewController()
            controller.body = self.textView.text
            controller.recipients = [self.phoneField.text!]
            controller.messageComposeDelegate = self
            self.presentViewController(controller, animated: true, completion: nil)
        }
        else
        {
            print("Error")
        }
    }

extension MyViewController : MFMessageComposeViewControllerDelegate 
{
    func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult)     
    {
            controller.dismissViewControllerAnimated(true, completion: nil)}
    }
}

Any Suggestions how can i send it to multiple recipients?


Solution

  • If user is entering multiple phone numbers in your textfield then you need to prompt the user to separate phone numbers using comma (or any other symbol) through which you can separate the string and add it into your array, then pass that array in controller.recipients

    here is an example

    if (MFMessageComposeViewController.canSendText())
            {
                let controller = MFMessageComposeViewController()
                controller.body = self.textView.text
                let phoneNumberString = "123456789,987654321,2233445566"
                let recipientsArray = phoneNumberString.components(separatedBy: ",")
                controller.recipients = recipientsArray
                controller.messageComposeDelegate = self
                self.presentViewController(controller, animated: true, completion: nil)
            }
            else
            {
                print("Error")
            }