iOS Swift: Get user selected phone number from CNContactProperty as a string [duplicate]

落花浮王杯 提交于 2019-12-09 04:24:26

So you said that you want to be able to get the phone number the user selected from the CNContactViewController.

The CNContactViewController has a delegate function that returns the key the user selected. This is the function:

optional func contactViewController(_ viewController: CNContactViewController, 
  shouldPerformDefaultActionFor property: CNContactProperty) -> Bool

In that function, you can get the selected phone number by doing this:

let myString = property.identifier

Also, if you return false in this function, the action wont take place which I think means it wont automatically call the number.

You can use this - although, if the contact has more than one phone number, this will only get the first one...

var thePhoneLabel: String?
var thePhoneNumber: String?

func contactPicker(picker: CNContactPickerViewController, didSelectContact contact: CNContact) {

    picker.dismissViewControllerAnimated(true, completion: {

        if contact.phoneNumbers.count > 0 {

            if let anEntry = contact.phoneNumbers.first {
                if let theNumber = anEntry.value as? CNPhoneNumber {

                    // Get the label for the phone number (Home, Work, Mobile, etc)
                    self.thePhoneLabel = CNLabeledValue.localizedStringForLabel(anEntry.label)

                    // Get the actual phone number (as a string)
                    self.thePhoneNumber = theNumber.stringValue

                }
            }

        } else {
            // contact has no phone numbers
            self.thePhoneLabel = "(No Phone)"
            self.thePhoneNumber = "(No Phone)"
        }

    })

}

EDIT:

If using:

contactPickerViewController.displayedPropertyKeys = [CNContactPhoneNumbersKey]

then:

var theContactName: String?
var thePhoneNumber: String?
var thePhoneLabel: String?

func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty) {

    theContactName = contactProperty.contact.givenName
    thePhoneNumber = contactProperty.value?.stringValue

    if let lbl = contactProperty.label {
        thePhoneLabel = CNLabeledValue.localizedStringForLabel(lbl)
    }

}

Note:

func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty)

function will only be called if you do NOT have a

func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!