Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract email from CNContactProperty - iOS 9

I have an iOS app which needs access to the Contacts picker view controller in order to allow the user to select a contact property such as email address/ telephone numbers of imessage email addresses.

The problem I am having right now, is that I can't figure out how to parse the returned data. I have made use of the contactPicker didSelectContactProperty method, but I am unable to parse the data I need.

-(void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {

   CNLabeledValue *test = contactProperty.contact.emailAddresses.firstObject;
   NSLog(@"%@", test);

   NSLog(@"%@", contactProperty.contact.phoneNumbers);
}

If you run the above code you get the following response:

2015-10-11 13:30:07.059 Actions[516:212765] <CNLabeledValue: 0x13656d090: identifier=21F2B1B2-8158-466B-9224-E2036CA07D28, label=_$!<Other>!$_, [email protected]> 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>>" )

Thats great, but how do I extract the data I need from it? Why are the NSLog statements returning the data in a weird format?

Thanks for your time, Dan.

like image 476
Supertecnoboff Avatar asked Oct 11 '15 12:10

Supertecnoboff


2 Answers

The returned values are of the CNLabeledValue class. In order to get the value from them, for, say, the emails, do this

CNLabeledValue *emailValue = contactProperty.contact.emailAddresses.firstObject;
NSString *emailString = emailValue.value;

If the value you wanted a phone number, this is how you would retrieve that

CNLabeledValue *phoneNumberValue = contactProperty.contact.phoneNumbers.firstObject;
CNPhoneNumber *phoneNumber = phoneNumberValue.value;
NSString *phoneNumberString = phoneNumber.stringValue;

Because the returned value is a CNLabeledValue, you are also able to retrieve the phone number's or email's label

NSString *emailLabel = emailValue.label; //This may be 'Work', 'Home', etc.
NSString *phoneNumberLabel = phoneNumberValue.label;
like image 114
Chris Loonam Avatar answered Oct 19 '22 23:10

Chris Loonam


For swift 3.0 :

 public func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact)
{
      if let emailValue : CNLabeledValue = contact.emailAddresses.first
    {
        txtEmail.text = emailValue.value as String
    }
    if let phoneNumber : CNLabeledValue = contact.phoneNumbers.first
    {
        txtMobno.text = phoneNumber.value.stringValue
    }
     txtFname.text = contact.givenName + " " + contact.familyName

}
like image 38
guru Avatar answered Oct 20 '22 00:10

guru