首先添加AddressBookUI.framework和AddressBook.framework库
然后配置plist文件,添加Privacy - Contacts Usage Description和描述
.h文件代码
#import
#import
#import
#define IS_iOS8 [[UIDevice currentDevice].systemVersion floatValue] >= 8.0f
#define IS_iOS6 [[UIDevice currentDevice].systemVersion floatValue] >= 6.0f
@interface ViewController : UIViewController
{
ABPeoplePickerNavigationController *_abPeoplePickerVc;
}
@property (nonatomic,strong) NSMutableDictionary *infoDictionary;
@end
.m文件代码
添加联系人数据源
_infoDictionary = [[NSMutableDictionary alloc] init];
_infoDictionary[@"name"] = @"cy";
_infoDictionary[@"phone"] = @"xxxxxxxxxx";
_infoDictionary[@"email"] = @"[email protected]";
_infoDictionary[@"Company"] = @"CY";
打开通讯录
/**
1.打开通讯录
*/
- (void)gotoAddressBook
{
_abPeoplePickerVc = [[ABPeoplePickerNavigationController alloc] init];
_abPeoplePickerVc.peoplePickerDelegate = self;
//下面的判断是ios8之后才需要加的,不然会自动返回app内部
if(IS_iOS8)
{
//predicateForSelectionOfPerson默认是true (当你点击某个联系人查看详情的时候会返回app),如果你默认为true 但是实现-peoplePickerNavigationController:didSelectPerson:property:identifier:
// 代理方法也是可以的,与此同时不能实现peoplePickerNavigationController: didSelectPerson:不然还是会返回app。
//总之在ios8之后加上此句比较稳妥
_abPeoplePickerVc.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
//predicateForSelectionOfProperty默认是true (当你点击某个联系人的某个属性的时候会返回app),此方法只要是默认值,无论你代理方法实现与否都会返回app。
// _abPeoplePickerVc.predicateForSelectionOfProperty = [NSPredicate predicateWithValue:false];
//predicateForEnablingPerson默认是true,当设置为false时,所有的联系人都不能被点击。
// _abPeoplePickerVc.predicateForEnablingPerson = [NSPredicate predicateWithValue:true];
}
[self presentViewController:_abPeoplePickerVc animated:YES completion:nil];
}
2.添加新的联系人(姓名、电话、email、公司)
//创建新的联系人
- (void)creatNewRecord
{
CFErrorRef error = NULL;
//创建一个通讯录操作对象
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
//创建一条新的联系人纪录
ABRecordRef newRecord = ABPersonCreate();
//为新联系人记录添加属性值
ABRecordSetValue(newRecord, kABPersonFirstNameProperty, (__bridge CFTypeRef)[_infoDictionary objectForKey:@"name"], &error);
//创建一个多值属性(电话)
ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)[_infoDictionary objectForKey:@"phone"], kABPersonPhoneMobileLabel, NULL);
ABRecordSetValue(newRecord, kABPersonPhoneProperty, multi, &error);
//添加email
ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiEmail, (__bridge CFTypeRef)([_infoDictionary objectForKey:@"email"]), kABWorkLabel, NULL);
ABRecordSetValue(newRecord, kABPersonEmailProperty, multiEmail, &error);
//
//Company公司
ABMutableMultiValueRef multiCompany = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiCompany, (__bridge CFTypeRef)([_infoDictionary objectForKey:@"Company"]), kABWorkLabel, NULL);
ABRecordSetValue(newRecord, kABPersonEmailProperty, multiCompany, &error);
//添加记录到通讯录操作对象
ABAddressBookAddRecord(addressBook, newRecord, &error);
//保存通讯录操作对象
ABAddressBookSave(addressBook, &error);
//通过此接口访问系统通讯录
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
if (granted) {
//显示提示
if (IS_iOS8) {
UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"添加成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[alertVc addAction:alertAction];
[self presentViewController:alertVc animated:YES completion:nil];
}else{
UIAlertView *tipView = [[UIAlertView alloc] initWithTitle:nil message:@"添加成功" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
[tipView show];
//非ARC
// [tipView release];
}
}
});
CFRelease(multiEmail);
CFRelease(multi);
CFRelease(newRecord);
CFRelease(addressBook);
}
3.需要实现的方法
#pragma mark - ABPeoplePickerNavigationController的代理方法
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
[phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
if (phone && phoneNO.length == 11) {
//TODO:获取电话号码要做的事情
[peoplePicker dismissViewControllerAnimated:YES completion:nil];
return;
}else{
if (IS_iOS8){
UIAlertController *tipVc = [UIAlertController alertControllerWithTitle:nil message:@"请选择正确手机号" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[tipVc addAction:cancleAction];
[self presentViewController:tipVc animated:YES completion:nil];
}else{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请选择正确手机号" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alertView show];
}
//非ARC模式需要释放对象
// [alertView release];
}
}
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person NS_AVAILABLE_IOS(8_0)
{
ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
personViewController.displayedPerson = person;
[peoplePicker pushViewController:personViewController animated:YES];
//非ARC模式需要释放对象
// [personViewController release];
}
/**
46 peoplePickerNavigationController点击取消按钮时调用
*/
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
[peoplePicker dismissViewControllerAnimated:YES completion:nil];
}
/**
54 iOS8被废弃了,iOS8前查看联系人必须实现(点击联系人可以继续操作)
*/
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person NS_DEPRECATED_IOS(2_0, 8_0)
{
return YES;
}
/**
62 iOS8被废弃了,iOS8前查看联系人属性必须实现(点击联系人属性可以继续操作)
*/
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier NS_DEPRECATED_IOS(2_0, 8_0)
{
ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
NSLog(@"%@", phoneNO);
if (phone && phoneNO.length == 11) {
//TODO:获取电话号码要做的事情
[peoplePicker dismissViewControllerAnimated:YES completion:nil];
return NO;
}else{
if (IS_iOS8){
UIAlertController *tipVc = [UIAlertController alertControllerWithTitle:nil message:@"请选择正确手机号" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[tipVc addAction:cancleAction];
[self presentViewController:tipVc animated:YES completion:nil];
}else{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请选择正确手机号" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alertView show];
}
}
return YES;
}
/**
2 添加联系人
*/
- (void)gotoAddContacts
{
//添加到通讯录,判断通讯录是否存在
if ([self isExistContactPerson]) {//存在,返回
//提示
if (IS_iOS8) {
UIAlertController *tipVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"联系人已存在..." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[tipVc addAction:cancleAction];
[self presentViewController:tipVc animated:YES completion:nil];
}else{
UIAlertView *tip = [[UIAlertView alloc] initWithTitle:@"提示" message:@"联系人已存在..." delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[tip show];
// [tip release];
}
return;
}else{//不存在 添加
[self creatNewRecord];
}
}
- (BOOL)isExistContactPerson
{
//这个变量用于记录授权是否成功,即用户是否允许我们访问通讯录
int __block tip=0;
BOOL __block isExist = NO;
//声明一个通讯簿的引用
ABAddressBookRef addBook =nil;
//因为在IOS6.0之后和之前的权限申请方式有所差别,这里做个判断
if (IS_iOS6) {
//创建通讯簿的引用,第一个参数暂时写NULL,官方文档就是这么说的,后续会有用,第二个参数是error参数
CFErrorRef error = NULL;
addBook=ABAddressBookCreateWithOptions(NULL, &error);
//创建一个初始信号量为0的信号
dispatch_semaphore_t sema=dispatch_semaphore_create(0);
//申请访问权限
ABAddressBookRequestAccessWithCompletion(addBook, ^(bool greanted, CFErrorRef error) {
//greanted为YES是表示用户允许,否则为不允许
if (!greanted) {
tip=1;
}else{
//获取所有联系人的数组
CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addBook);
//获取联系人总数
CFIndex number = ABAddressBookGetPersonCount(addBook);
//进行遍历
for (NSInteger i=0; iGeneral>Privacy" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[tipVc addAction:cancleAction];
[tipVc presentViewController:tipVc animated:YES completion:nil];
}else{
UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"友情提示" message:@"请您设置允许APP访问您的通讯录\nSettings>General>Privacy" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alart show];
//非ARC
// [alart release];
}
}
return isExist;
}