iOS Swift:从CNContactProperty获取用户select的电话号码作为string

如标题所示,在我使用swift的iOS应用程序中,我有一个CNContactProperty对象,我想从中提取电话号码作为string。

CNContact属性通过委托协议function从标准的CNContactPickerViewController返回,在用户select了一个联系人之后。

当联系人有多个电话号码时,我希望能够从CNContactProperty中提取用户在联系人视图中点击的电话号码。

我正在尝试做这样的事情:

let myString = theCNContactProperty.value as! String 

但是,这个崩溃(lldb)错误。 我怀疑也许“价值”财产不是我所需要的?

我能够像这样检索任意数字:

 let myString = contactProperty.contact.phoneNumbers[0].value.stringValue 

哪个返回联系人的第一个号码。 然而,这不符合我的目的,因为我想能够提取用户select的具体数字,当一个联系人有多个号码。

我一直在这个工作几个小时,无法弄清楚,我会很感激任何帮助,你可以给我!

编辑:这不是所提供的链接的副本。 链接的问题是关于检索联系人的所有号码,而不是一个特别select的。 在这方面有很大的不同。

所以你说你想能够获得用户从CNContactViewControllerselect的电话号码。

CNContactViewController有一个委托函数,返回用户select的键。 这是function:

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

在该function中,您可以通过执行以下操作获取选定的电话号码:

 let myString = property.identifier 

另外,如果你在这个函数中返回false,这个动作不会发生,我认为它不会自动调用这个数字。

你可以使用这个 – 虽然,如果联系人有多个电话号码,这只会得到第一个…

 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)" } }) } 

编辑:

如果使用:

 contactPickerViewController.displayedPropertyKeys = [CNContactPhoneNumbersKey] 

然后:

 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) } } 

注意:

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

函数只会被调用,如果你没有一个

func contactPicker(_ picker:CNContactPickerViewController,didSelect联系人:CNContact)