CNContactPickerViewController is used to show contacts in TableView. It allows the user to select one or more contacts (or their properties) from the list of contacts displayed in the contact view controller (CNContactViewController).
Suppose we want to show a contact list on button click action so for that first import #import <ContactsUI/ContactsUI.h> in your project .
Add CNContactPickerDelegate also in your controller class. As done below
@interface ViewController : UIViewController<CNContactPickerDelegate>
In button action write below code.
- (IBAction)btnShowContacts:(id)sender {
CNContactPickerViewController *contactPickerController=[[CNContactPickerViewController alloc]init];
[self presentViewController:contactPickerController animated:YES completion:nil];
contactPickerController.delegate=self;
}
Now when you run the code you will get complete contact list.
Delegate methods of CNcontactPicker
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact
{
[self dismissViewControllerAnimated:YES completion:nil];
NSString *fetchName = contact.givenName;
NSArray *fetchPhoneNo = contact.phoneNumbers;
NSLog(@"contact details are %@ %@ ",fetchPhoneNo,fetchName);
}
We can also fetch the further details by using below code
- (void)parseContactWithContact :(CNContact* )contact
{
//givenName,phoneNumbers,emailAddresses and familyName are the inbuilt properties of CNContactPicker
NSString * firstName = contact.givenName;
NSString * lastName = contact.familyName;
NSString * phone = [[contact.phoneNumbers valueForKey:@"value"] valueForKey:@"digits"];
NSString * email = [contact.emailAddresses valueForKey:@"value"];
NSLog(@"%@ %@ %@ %@",firstName,lastName,phone,email);
}
Below code is used to fetch address
- (NSMutableArray *)parseAddressWithContac: (CNContact *)contact
{
NSMutableArray * addressArray = [[NSMutableArray alloc]init];
CNPostalAddressFormatter * formatter = [[CNPostalAddressFormatter alloc]init];
NSArray * addresses = (NSArray*)[contact.postalAddresses valueForKey:@"value"];
if (addresses.count > 0) {
for (CNPostalAddress* newAddress in addresses) {
[addressArray addObject:[formatter stringFromPostalAddress:newAddress]];
}
}
return addressArray;
}
Some more delegate methods
* - contactPickerDidCancel: -> when user taps cancel
* - contactPicker:didSelectContact: -> Called after a contact has been selected by the user
* - contactPicker:didSelectContactProperty: -> When a property of contact selected by a user
For example->
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty
{
//This delegate method is called when the user selects a single property of the contact.
}
2 Comment(s)