How Get Data Contact Use CNContactPickerViewController



Get user selected phone number from CNContactProperty and extract the phone number from it as a string. first "import ContactsUI" In button action add this code:


import ContactsUI
import UIKit

class PickContactViewController: UIViewController {
    @IBOutlet weak var contactLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func handleContact(_ sender: UIButton) {
        let contacVC = CNContactPickerViewController()
        contacVC.delegate = self
        contacVC.displayedPropertyKeys = [CNContactGivenNameKey, CNContactPhoneNumbersKey]
        self.present(contacVC, animated: true, completion: nil)
    }
}


After add CNContactPickerDelegate in your viewcontroller  call function  didSelectContact Or didSelectContactProperty for action select phone number.

didSelectContact - if you need only one phone number
didSelectContactProperty - when the contact has more than one phone number

---didSelectContact (Just get PhoneNumber)

extension PickContactViewController: CNContactPickerDelegate {
// MARK: Delegate method CNContectPickerDelegate if just select 1 phone number private func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) { let numbers = contact.phoneNumbers.first print((numbers?.value)?.stringValue ?? "") let text = (numbers?.value)?.stringValue.replacingOccurrences(of: "-", with: "", options: NSString.CompareOptions.literal, range: nil) let text2 = text?.replacingOccurrences(of: " ", with: "", options: NSString.CompareOptions.literal, range: nil) self.contactLabel.text = " Contact No. \(text2 ?? "")" } func contactPickerDidCancel(_ picker: CNContactPickerViewController) { self.dismiss(animated: true, completion: nil) } }

OR
--didSelectContactProperty (Get More ->"Name, email, phone number, etc")

extension PickContactViewController: CNContactPickerDelegate {

    // MARK: Delegate method CNContectPickerDelegate for select more than 1 phone number and username
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) {

        let phone = contactProperty.contact.phoneNumbers.first?.value.stringValue
        let phoneName = contactProperty.contact.givenName
        print("Phone: \(phone ?? "")", "Name: \(phoneName)")
       self.contactLabel.text = " Contact No: \(phone ?? "")"       
    }

   func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        self.dismiss(animated: true, completion: nil)
    }

}


Note plus:  Check all contact in one contact name

for check all  -> print(data.value.stringValue)
for check by index -> print(data[0].value.stringValue)

  // check all contact
        contactProperty.contact.phoneNumbers.forEach { data in
            print(data.value.stringValue, "Phone",data[0].value.stringValue)
            
        }




No comments: