General Middleware

Fetch User Contacts with CNContactPickerDelegate in Swift

Follow below steps to pop the Contacts List and choose one from there.

  1. Import ContactsUI into the ViewController
  2. Make your ViewController extend CNContactPickerDelegate.
  3. Create a button called “Add Contact” in Main.storyboard
  4. Link the below IBAction method and link it to the button created in Step 3.
    @IBAction func addContacts(_ sender: Any) {
        let contactPicker = CNContactPickerViewController()
        contactPicker.delegate = self
        present(contactPicker, animated: true) {
            print("Do something after contact has been picked ...")
        }
    }

5. Implement the below delegate method, where you receive the selected contact.

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        print("Contact Selected = \(contact.phoneNumbers[0])")
    }

Combining all the code above, here is the consolidated ViewController code

import UIKit
import ContactsUI

class ViewController: UIViewController, CNContactPickerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    @IBAction func addContacts(_ sender: Any) {
        let contactPicker = CNContactPickerViewController()
        contactPicker.delegate = self
        present(contactPicker, animated: true) {
            print("Do something after contact has been picked ...")
        }
    }
    
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        print("Contact Selected = \(contact.phoneNumbers[0])")
    }
    
}

Leave a Reply

Your email address will not be published. Required fields are marked *