#import "ViewController.h"
#import <ContactsUI/ContactsUI.h>
//#import <AddressBookUI/AddressBookUI.h>
@interface ViewController ()<CNContactPickerDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
#pragma mark 点击屏幕来显示联系人界面
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//1. 创建联系人选择控制器
CNContactPickerViewController *picker = [CNContactPickerViewController new];
//2. 设置代理 --> 获取数据
picker.delegate = self;
//3. 模态弹出控制器
[self presentViewController:picker animated:YES completion:nil];
}
/**
如果实现了多选联系人, 单选联系人就失效
*/
#pragma mark 选中联系人的时候会调用
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact
{
//获取联系人的电话和姓名
//1. 获取姓名
// 名
NSLog(@"%@", contact.givenName);
// 姓
NSLog(@"%@", contact.familyName);
//2. 获取电话
for (CNLabeledValue *labeledValue in contact.phoneNumbers) {
NSLog(@"label: %@", labeledValue.label);
//ValueType == CNPhoneNumber
CNPhoneNumber *phoneNumber = labeledValue.value;
NSLog(@"value: %@", phoneNumber.stringValue);
}
}
#pragma mark 选中多个联系人的时候回调用
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts
{
for (CNContact *contact in contacts) {
//1. 获取姓名
// 名
NSLog(@"%@", contact.givenName);
// 姓
NSLog(@"%@", contact.familyName);
//2. 获取电话
for (CNLabeledValue *labeledValue in contact.phoneNumbers) {
NSLog(@"label: %@", labeledValue.label);
//ValueType == CNPhoneNumber
CNPhoneNumber *phoneNumber = labeledValue.value;
NSLog(@"value: %@", phoneNumber.stringValue);
}
}
}
//#pragma mark 选中联系人的属性的时候会调用
//- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty
//{
//
//}
//
//#pragma mark 选中联系人的多个属性的时候会调用
//- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperties:(NSArray<CNContactProperty *> *)contactProperties
//{
//
//}
#pragma mark 取消联系人界面的时候会调用的方法
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker
{
NSLog(@"%s", __func__);
}
@end