#import "ViewController.h" #import <ContactsUI/ContactsUI.h> @interface ViewController ()<CNContactPickerDelegate> { UIButton * btn; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; btn = [UIButton buttonWithType:UIButtonTypeCustom]; [btn setTitle:@"通讯录" forState:UIControlStateNormal]; btn.frame = CGRectMake(0, 100, 200, 200); btn.backgroundColor = [UIColor cyanColor]; [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; [btn addTarget:self action:@selector(pressBtn) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; } -(void)pressBtn{ //让用户给权限,没有的话会被拒的各位 CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]; if (status == CNAuthorizationStatusNotDetermined) { CNContactStore *store = [[CNContactStore alloc] init]; [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) { if (error) { NSLog(@"weishouquan "); }else { NSLog(@"chenggong ");//用户给权限了 CNContactPickerViewController * picker = [CNContactPickerViewController new]; picker.delegate = self; picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];//只显示手机号 [self presentViewController: picker animated:YES completion:nil]; } }]; } if (status == CNAuthorizationStatusAuthorized) {//有权限时 CNContactPickerViewController * picker = [CNContactPickerViewController new]; picker.delegate = self; picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey]; [self presentViewController: picker animated:YES completion:nil]; } else{ NSLog(@"您未开启通讯录权限,请前往设置中心开启"); } } -(void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{ CNPhoneNumber * num = nil; NSString * string = nil; if (contact.phoneNumbers.count >0) { num = contact.phoneNumbers[0].value; string = [NSString stringWithFormat:@"%@%@%@",contact.familyName,contact.givenName,[num valueForKey:@"digits"]]; }else{ string = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName]; } NSLog(@"%@",string);//2016-12-12 10:28:06.823028 通讯录[17274:5041432] 滴滴出行4001809660 [btn setTitle:string forState:UIControlStateNormal]; }