正如标题所示,在我使用swift的iOS应用程序中,我有一个CNContactProperty对象,我想从中提取电话号码作为字符串。
在用户从中选择联系人后,CNContact属性通过委托协议函数从标准CNContactPickerViewController返回。
当联系人有多个电话号码时,我希望能够从CNContactProperty中提取用户在联系人视图中点击的电话号码。
我试图做这样的事情:
let myString = theCNContactProperty.value as! String
但是,这会因(lldb)错误而崩溃。我怀疑可能是"值"财产不是我需要的?
我能够像这样检索任意数字:
let myString = contactProperty.contact.phoneNumbers[0].value.stringValue
返回联系人的第一个号码。但是,这并不符合我的目的,因为我希望能够在联系人数超过1时提取用户选择的特定号码。
我已经在这方面工作了好几个小时而且无法弄清楚,我很感激你能给我的任何帮助!
编辑:这不是提供的链接的副本。链接的问题是从联系人中检索所有号码,而不是专门选择的号码。这有很大的不同。
答案 0 :(得分:0)
你可以使用它 - 但是,如果联系人有多个电话号码,这只会得到第一个......
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)
答案 1 :(得分:0)
所以你说你希望能够获得用户从CNContactViewController
中选择的电话号码。
CNContactViewController
有一个委托函数,用于返回用户选择的密钥。这是功能:
optional func contactViewController(_ viewController: CNContactViewController,
shouldPerformDefaultActionFor property: CNContactProperty) -> Bool
在该功能中,您可以通过以下方式获取所选的电话号码:
let myString = property.identifier
另外,如果你在这个函数中返回false,那么动作就不会发生,我认为这意味着它不会自动调用该数字。