详解iOS获取通讯录的4种方式

2020-01-18 16:42:26王振洲

运行结果:

iOS获取通讯录,iOS通讯录的获取

ContactsUI.framework


#import "ViewController.h"
#import <ContactsUI/ContactsUI.h>

@interface ViewController () <CNContactPickerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  CNContactPickerViewController *contactPickerViewController = [[CNContactPickerViewController alloc] init];
  contactPickerViewController.delegate = self;

  [self presentViewController:contactPickerViewController animated:YES completion:nil];
}


// 如果实现该方法当选中联系人时就不会再出现联系人详情界面, 如果需要看到联系人详情界面只能不实现这个方法,
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
  NSLog(@"选中某一个联系人时调用---------------------------------");

  [self printContactInfo:contact];
}

// 同时选中多个联系人
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts {
  for (CNContact *contact in contacts) {
    NSLog(@"================================================");
    [self printContactInfo:contact];
  }
}

- (void)printContactInfo:(CNContact *)contact {
  NSString *givenName = contact.givenName;
  NSString *familyName = contact.familyName;
  NSLog(@"givenName=%@, familyName=%@", givenName, familyName);
  NSArray * phoneNumbers = contact.phoneNumbers;
  for (CNLabeledValue<CNPhoneNumber*>*phone in phoneNumbers) {
    NSString *label = phone.label;
    CNPhoneNumber *phonNumber = (CNPhoneNumber *)phone.value;
    NSLog(@"label=%@, value=%@", label, phonNumber.stringValue);
  }
}
// 注意:如果实现该方法,上面那个方法就不能实现了,这两个方法只能实现一个
//- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {
//  NSLog(@"选中某个联系人的某个属性时调用");
//}

@end

选择单个联系人时运行效果:

iOS获取通讯录,iOS通讯录的获取

iOS获取通讯录,iOS通讯录的获取

选择多个联系人的界面:

iOS获取通讯录,iOS通讯录的获取

iOS获取通讯录,iOS通讯录的获取