调起
eg:
//ContactsUI.framework中
CNContactPickerViewController *contactVC = [CNContactPickerViewController new];
contactVC.delegate = self;
[self presentViewController:contactVC animated:YES completion:^{
}];
添加授权
CNContactStore *contactStore = [[CNContactStore alloc] init];
[contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
// 成功
} else {
// 失败
}
}];
代理方法
#pragma mark - CNContactViewControllerDelegate代理
//选择一个联系人的时候调用
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{
//1.姓名
NSLog(@"%@-%@",contact.givenName,contact.familyName);
//2.获取电话 --->泛型,会在遍历数组帮很大忙。
for (CNLabeledValue *labelValue in contact.phoneNumbers) {
NSLog(@"电话标签: %@",labelValue.label);
CNPhoneNumber *phoneNumber = labelValue.value;
NSLog(@"电话号码: %@",phoneNumber.stringValue);
}
}
//实现此方法就可以选择多个联系人,如果不实现则是单选联系人
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts{
for (CNContact *contact in contacts) {
//1.姓名
NSLog(@"%@-%@",contact.givenName,contact.familyName);
//2.获取电话 --->泛型,会在遍历数组帮很大忙。
for (CNLabeledValue *labelValue in contact.phoneNumbers) {
NSLog(@"电话标签: %@",labelValue.label);
CNPhoneNumber *phoneNumber = labelValue.value;
NSLog(@"电话号码: %@",phoneNumber.stringValue);
}
NSLog(@"\n\n");
}
}
//选择联系人属性
//- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty{
//
//}
//- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperties:(NSArray<CNContactProperty *> *)contactProperties{
//
//}
//取消选择联系人的时候调用
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker{
}