0

Im trying to acheive the same results as: Sending SMS from Contacts Fails

  • Sending an SMS or "App Invite" to contact(s).

The solution to this problem works, but it only allows you to send an SMS to one person at a time. What I want to do is send an SMS to multiple contacts at one time. Forgive me if this is fairly easy. I've been up for the past 14 hours programming and most things aren't making sense to me right now.

Heres my code:

 //MARK : VARIABLES
let contactPickerViewController = CNContactPickerViewController()
let messageViewController = MFMessageComposeViewController()


//MARK : VIEW DID LOAD
override func viewDidLoad() {
    super.viewDidLoad()

    //-- set delegates equal to self
    contactPickerViewController.delegate = self
    messageViewController.messageComposeDelegate = self
}

//MARK : MFMESSAGECOMPOSE & CNCONTACTPICKERDELEGATE

func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
    self.dismiss(animated: true, completion: nil)
}


func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
    //-- select contacts and present message compose view controller
    contacts.forEach { (contact) in
        for data in contact.phoneNumbers {
            let phoneNo = data.value

            //-- configure message view controller
            messageViewController.recipients = [phoneNo]
            messageViewController.body = "Testing Testing"

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.present(self.messageViewController, animated: true, completion: nil)
            })
        }
    }
}

func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
    print("cancelled")
}
Vandal
  • 708
  • 1
  • 8
  • 21

1 Answers1

1

In your for loop you are attempting to display an MFMessageComposeViewController for each recipient. This won't work as it will attempt to present multiple view controllers concurrently.

You can present a single MFMessageComposeViewController that has all of the recipients specified:

var recipients = [String]()
contacts.forEach { (contact) in
    for data in contact.phoneNumbers {
        let phoneNo = data.value
        recipients.append(phoneNo.stringValue)
    }
}

//-- configure message view controller
messageViewController.recipients = recipients
messageViewController.body = "Testing Testing"

self.present(self.messageViewController, animated: true, completion: nil)
Paulw11
  • 108,386
  • 14
  • 159
  • 186