我有一个iOS应用程序,需要访问联系人选择器视图控制器,以允许用户选择联系人属性,如电子邮件地址/ imessage电子邮件地址的电话号码。
我现在遇到的问题是,我无法弄清楚如何解析返回的数据。我已经使用了contactPicker didSelectContactProperty
方法,但我无法解析我需要的数据。
-(void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {
CNLabeledValue *test = contactProperty.contact.emailAddresses.firstObject;
NSLog(@"%@", test);
NSLog(@"%@", contactProperty.contact.phoneNumbers);
}
如果您运行上述代码,则会收到以下响应:
2015-10-11 13:30:07.059 Actions[516:212765] <CNLabeledValue: 0x13656d090: identifier=21F2B1B2-8158-466B-9224-E2036CA07D28, label=_$!<Other>!$_, value=News_Europe@iEUNS.com> 2015-10-11 13:30:07.061 App_Name[516:212765] (
"<CNLabeledValue: 0x13672a500: identifier=6697A0E9-3B91-4566-B26E-83B87979F816, label=_$!<Main>!$_, value=<CNPhoneNumber: 0x13672a660: countryCode=gb, digits=08000391010>>" )
太好了,但是如何从中提取我需要的数据呢?为什么NSLog语句以奇怪的格式返回数据?
谢谢你的时间,Dan。
答案 0 :(得分:14)
返回的值属于CNLabeledValue类。为了从电子邮件中获取价值,比如电子邮件,请执行此操作
CNLabeledValue *emailValue = contactProperty.contact.emailAddresses.firstObject;
NSString *emailString = email.value;
如果您想要一个电话号码的值,这就是您检索
的方式CNLabeledValue *phoneNumberValue = contactProperty.contact.phoneNumbers.firstObject;
CNPhoneNumber *phoneNumber = phoneNumberValue.value;
NSString *phoneNumberString = phoneNumber.stringValue;
由于返回的值为CNLabeledValue
,您还可以检索电话号码或电子邮件的标签
NSString *emailLabel = emailValue.label; //This may be 'Work', 'Home', etc.
NSString *phoneNumberLabel = phoneNumberValue.label;
答案 1 :(得分:0)
Here is swift version of Chris answer :
func fatchContacts(store : CNContactStore) {
do
{
let groups = try store.groups(matching: nil)
let predicate = CNContact.predicateForContactsInGroup(withIdentifier: groups[0].identifier)
//let predicate = CNContact.predicateForContactsMatchingName("John")
let keyToFatch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName ) ,CNContactEmailAddressesKey] as [Any]
let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keyToFatch as! [CNKeyDescriptor]) //------------------------------------------------------
//-------------Get Here-----------------------------------------
print(contacts)
print(contacts[0])
let formatter = CNContactFormatter ()
print(formatter.string(from: contacts[0]))
print(contacts[0].givenName)
print(contacts[0].emailAddresses)
let emailValue : CNLabeledValue = contacts[0].emailAddresses.first!;
let email = emailValue.value
print(email)
}
catch{
}
}
Just pass the CNContactStore object
答案 2 :(得分:0)
不幸的是,克里斯(Chris)的答案告诉您如何从返回的CNLabeledValue对象获取值,但没有告诉您如何识别函数功能基于contactProperty参数选择的CNLabeledValue。
您需要做的是循环浏览每个联系人的电子邮件地址,并检查其标识符是否与所选的contactProperty标识符匹配。在didSelectContactProperty函数内使用以下代码:
NSString *selectedEmail;
for (CNLabeledValue<NSString*>* email in contactProperty.contact.emailAddresses) {
if ([email.identifier isEqualToString:contactProperty.identifier]) {
selectedEmail = (NSString *)email.value;
}
}
请注意,我只用邮政地址测试了此代码,因此可能需要做一些进一步的调整才能使用电子邮件地址。