Sending SMS from contacts

I implement a seemingly trivial and very popular use case when users select a contact and send them a pre-configured SMS.

However, SMS ViewController is automatically rejected. It is easy to reproduce.

How to fix it?

Here is my code:

import UIKit
import MessageUI
import ContactsUI

class ViewController: UIViewController, MFMessageComposeViewControllerDelegate, CNContactPickerDelegate{

    let contactPickerViewController = CNContactPickerViewController()
    let messageVC = MFMessageComposeViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
        contactPickerViewController.delegate = self

        messageVC.messageComposeDelegate = self
    }

    func contactPicker(picker: CNContactPickerViewController, didSelectContact contact: CNContact) {
        if let phoneNumberValue = contact.phoneNumbers.first?.value as? CNPhoneNumber {
            if let phoneNumber = phoneNumberValue.valueForKey("digits") as? String {

                // Configure message ViewController
                messageVC.recipients = [phoneNumber]
                messageVC.body = "Yoyoyo"

                picker.presentViewController(messageVC, animated: true, completion: nil)
            }
        }
    }

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

    @IBAction func invite(sender: AnyObject) {
        self.presentViewController(self.contactPickerViewController, animated: true, completion: nil)

    }
}
+4
source share
1 answer

, . contactPicker: picker: didSelectContact: method, . , , .

, "ViewController" . . , . , VVC, , .

func contactPicker(picker: CNContactPickerViewController, didSelectContact contact: CNContact) {
    if let phoneNumberValue = contact.phoneNumbers.first?.value as? CNPhoneNumber {
        if let phoneNumber = phoneNumberValue.valueForKey("digits") as? String {

            // Configure message ViewController
            messageVC.recipients = [phoneNumber]
            messageVC.body = "Yoyoyo"

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.presentViewController(self.messageVC, animated: true, completion: nil)
            })
        }
    }
}
+3

Source: https://habr.com/ru/post/1623986/


All Articles