Search code examples
iosswiftxcodecontactspicker

Contact picker in ios to get phone number


enter image description hereI need an option like image picker for picking contact and to display phone number i have managed to get contact names using below code

by using this code it only returns the names , need an option to pick contact from contact list


Solution

  • import ContactsUI
    and include - CNContactPickerDelegate

    import ContactsUI
    
    class YourViewController: CNContactPickerDelegate{
    
        //MARK:- contact picker
        func onClickPickContact(){
    
    
            let contactPicker = CNContactPickerViewController()
            contactPicker.delegate = self
            contactPicker.displayedPropertyKeys =
                [CNContactGivenNameKey
                    , CNContactPhoneNumbersKey]
            self.present(contactPicker, animated: true, completion: nil)
    
        }
    
        func contactPicker(_ picker: CNContactPickerViewController,
                           didSelect contactProperty: CNContactProperty) {
    
        }
    
        func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
            // You can fetch selected name and number in the following way
    
            // user name
            let userName:String = contact.givenName
    
            // user phone number
            let userPhoneNumbers:[CNLabeledValue<CNPhoneNumber>] = contact.phoneNumbers
            let firstPhoneNumber:CNPhoneNumber = userPhoneNumbers[0].value
    
    
            // user phone number string
            let primaryPhoneNumberStr:String = firstPhoneNumber.stringValue
    
            print(primaryPhoneNumberStr)
    
        }
    
        func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
    
        }
    }