ios调用通讯录以及选择联系人列表方法

先把Demo双手奉上我是Demo传送门
首先在info.plist里面添加读取通讯录的权限

通讯录权限: Privacy - Contacts Usage Description 是否允许此App访问你的通讯录?

然后再写一个宏判断系统版本,这样可以根据 ios9 来判断使用哪一种系统框架

#define IOS_VERSION_9_OR_AFTER (([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)? (YES):(NO))

ios 9 之前的框架----AddressBook Framework

导入框架AddressBook.Framework,需要UI就导入 AddressBookUI.Framework

导入头文件#import <AddressBook/AddressBook.h>

//获取通讯录数组

+(NSArray *)getIOS9BeforeAddressBooks

{
NSMutableArray *peopleArray = [NSMutableArray array];
    
    int __block tip = 0;
    
    ABAddressBookRef addBook = nil;
    
    addBook = ABAddressBookCreateWithOptions(NULL, NULL);
    
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    
    ABAddressBookRequestAccessWithCompletion(addBook, ^(bool greanted, CFErrorRef error){
        if (!greanted) {
            tip = 1;
        }
        dispatch_semaphore_signal(sema);
    });
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    
    if (tip) {
        //        ChooseAlertShow(@"请您设置允许APP访问您的通讯录\n设置>通用>隐私");
        return nil;
    }
    
    CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addBook);
    
    CFIndex number = ABAddressBookGetPersonCount(addBook);
    
    for (int i = 0; i < number; i++) {
        
        ABRecordRef  people = CFArrayGetValueAtIndex(allLinkPeople, i);
        
        CFTypeRef abName = ABRecordCopyValue(people, kABPersonFirstNameProperty);
        CFTypeRef abLastName = ABRecordCopyValue(people, kABPersonLastNameProperty);
        CFStringRef abFullName = ABRecordCopyCompositeName(people);
        NSString *nameString = (__bridge NSString *)abName;
        NSString *lastNameString = (__bridge NSString *)abLastName;
        
        if ((__bridge id)abFullName != nil) {
            nameString = (__bridge NSString *)abFullName;
        } else {
            if ((__bridge id)abLastName != nil)
            {
                nameString = [NSString stringWithFormat:@"%@ %@", nameString, lastNameString];
            }
        }
        //读取电话多值
        NSString *phoneStr = @"";
        ABMultiValueRef phone = ABRecordCopyValue(people, kABPersonPhoneProperty);
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //获取电话Label
            //            NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
            //获取該Label下的电话值
            NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
            
            phoneStr = [phoneStr stringByAppendingFormat:@"%@ ",personPhone];
        }
        
        NSString * note = (__bridge NSString*)(ABRecordCopyValue(people, kABPersonNoteProperty));
        
        NSString *email = @"";
        //获取email多值
        ABMultiValueRef emailRef = ABRecordCopyValue(people, kABPersonEmailProperty);
        
        for (int x = 0; x < ABMultiValueGetCount(emailRef); x++)
        {
            //获取email Label
            //            NSString* emailLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(emailRef, x));
            //获取email值
            email = (__bridge NSString*)ABMultiValueCopyValueAtIndex(emailRef, x);
            
            
        }
        //读取jobtitle工作
        NSString *jobtitle = (__bridge NSString*)ABRecordCopyValue(people, kABPersonJobTitleProperty);
        
        //读取nickname呢称
        NSString *nickname = (__bridge NSString*)ABRecordCopyValue(people, kABPersonNicknameProperty);
        
        NSString * organization = (__bridge NSString*)(ABRecordCopyValue(people, kABPersonOrganizationProperty));
        
        NSDate *birthDate = (__bridge NSDate *)(ABRecordCopyValue(people, kABPersonBirthdayProperty));
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        dateFormatter.dateFormat = @"yyyy-MM-dd";
        
        NSString *birthday = @"";
        if (birthDate) {
            birthday = [dateFormatter stringFromDate:birthDate];
        }
        
        //第一次添加该条记录的时间
        NSDate *createDate = (__bridge NSDate*)ABRecordCopyValue(people, kABPersonCreationDateProperty);
        NSString *createTime = @"";
        if (createDate) {
            createTime = [dateFormatter stringFromDate:createDate];
        }
        
        //最后一次修改該条记录的时间
        NSDate *modifyDate = (__bridge NSDate*)ABRecordCopyValue(people, kABPersonModificationDateProperty);
        
        NSString *modifyTime = @"";
        if (modifyDate) {
            modifyTime = [dateFormatter stringFromDate:modifyDate];
        }
        //读取地址多值
        ABMultiValueRef address = ABRecordCopyValue(people, kABPersonAddressProperty);
        NSString *addressStr = @"";
        for(int j = 0; j < ABMultiValueGetCount(address); j++)
        {
            //获取地址Label
            //            NSString* addressLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(address, j);
            
            //获取該label下的地址6属性
            NSDictionary* personaddress =(__bridge NSDictionary*) ABMultiValueCopyValueAtIndex(address, j);
            NSString* country = [personaddress valueForKey:(NSString *)kABPersonAddressCountryKey];
            if(country != nil)
                addressStr = [addressStr stringByAppendingFormat:@"%@ ",country];
            NSString* city = [personaddress valueForKey:(NSString *)kABPersonAddressCityKey];
            if(city != nil)
                addressStr = [addressStr stringByAppendingFormat:@"%@ ",city];
            NSString* state = [personaddress valueForKey:(NSString *)kABPersonAddressStateKey];
            if(state != nil)
                addressStr = [addressStr stringByAppendingFormat:@"%@ ",state];
            NSString* street = [personaddress valueForKey:(NSString *)kABPersonAddressStreetKey];
            if(street != nil)
                addressStr = [addressStr stringByAppendingFormat:@"%@ ",street];
            //            NSString* zip = [personaddress valueForKey:(NSString *)kABPersonAddressZIPKey];
            //            if(zip != nil)
            //                addressStr = [addressStr stringByAppendingFormat:@"邮编:%@",zip];
            
        }
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        
        [dict setObject:nameString.length != 0 ? nameString : @"" forKey:@"contact_name"];
        
        [dict setObject:phoneStr forKey:@"phone_no"];
        
        [dict setObject:email forKey:@"email"];
        
        [dict setObject:organization.length != 0 ? organization : @"" forKey:@"organization"];
        
        [dict setObject:addressStr forKey:@"address"];
        
        [dict setObject:birthday != nil ? birthday :@"" forKey:@"birthday"];
        
        [dict setObject:jobtitle.length != 0 ? jobtitle : @"" forKey:@"job_title"];
        
        [dict setObject:nickname.length != 0 ? nickname : @"" forKey:@"nickname"];
        
        [dict setObject:note.length != 0 ? note : @"" forKey:@"note"];
        
        [dict setObject:createTime forKey:@"create_time"];
        
        [dict setObject:modifyTime forKey:@"modify_time"];
        
        [peopleArray addObject:dict];
        
        if(abName) CFRelease(abName);
        if(abLastName) CFRelease(abLastName);
        if(abFullName) CFRelease(abFullName);
        if(people) CFRelease(people);
    }
    if(allLinkPeople) CFRelease(allLinkPeople);
    
    return peopleArray;

}
//查看是否有权限读取通讯录

+(void)CheckAddressBookIOS9BeforeAuthorization:(void (^)(bool isAuthorized))block

{

ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);

ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();

if (authStatus != kABAuthorizationStatusAuthorized)

{

ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)

{

dispatch_async(dispatch_get_main_queue(), ^{

if (!granted)

{

block(NO);

}

else

{

block(YES);

}

});

});

}

else{

block(YES);

}

}

ios 9之后的框架-----Contacts Framework

导入框架Contacts.Framework,需要UI就导入 ContactsUI.Framework导入头文件

导入#import <Contacts/Contacts.h>

//ios 9 以后 使用block 返回 联系人数组

+(void)getIOS9AfterContactsSuccess:(void (^)(NSArray *))block

{

NSMutableArray *contacts = [NSMutableArray array];
    
    if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized) {
        
        CNContactStore *store = [[CNContactStore alloc] init];
        
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                
                CNContactStore * store = [[CNContactStore alloc] init];
                //这里写要获取的内容的key
                NSArray * keys = @[CNContactGivenNameKey, CNContactFamilyNameKey,CNContactNicknameKey, CNContactOrganizationNameKey,CNContactBirthdayKey,CNContactNoteKey,CNContactJobTitleKey,CNContactPhoneNumbersKey,CNContactEmailAddressesKey,CNContactPostalAddressesKey,CNContactDatesKey];
                
                CNContactFetchRequest * request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
                
                [store enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
                    
                    NSString *nameString = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
                    
                    NSString *phoneStr = @"";
                    
                    for (CNLabeledValue * labelValue in contact.phoneNumbers) {
                        
                        CNPhoneNumber * number = labelValue.value;
                        
                        phoneStr  = [phoneStr stringByAppendingFormat:@"%@ ",number.stringValue];
                    }
                    
                    NSString *email = @"";
                    
                    for (CNLabeledValue * valueStr in contact.emailAddresses) {
                        
                        NSString * emailStr = valueStr.value;
                        
                        email  = [email stringByAppendingFormat:@"%@",emailStr];
                    }
                    
                    NSString *addressStr = @"";
                    
                    for (CNLabeledValue * labelValue in contact.postalAddresses) {
                        
                        CNPostalAddress * postalAddress = labelValue.value;
                        
                        addressStr = [NSString stringWithFormat:@"%@ %@ %@ %@",postalAddress.country,postalAddress.city,postalAddress.state,postalAddress.street];
                    }
                    
                    NSString *nickname = contact.nickname;
                    
                    NSString *note = contact.note;
                    
                    NSString *jobtitle = contact.jobTitle;
                    
                    NSString *organization = contact.organizationName;
                    NSString *birthday = @"";
                    if (contact.birthday) {
                        NSDateComponents *dateCom = contact.birthday;
                        birthday = [NSString stringWithFormat:@"%ld-%ld-%ld",(long)dateCom.year,(long)dateCom.month,(long)dateCom.day];
                    }
                    
                    
                    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                    
                    [dict setObject:nameString.length != 0 ? nameString : @"" forKey:@"contact_name"];
                    
                    [dict setObject:phoneStr forKey:@"phone_no"];
                    
                    [dict setObject:email forKey:@"email"];
                    
                    [dict setObject:organization.length != 0 ? organization : @"" forKey:@"organization"];
                    
                    [dict setObject:addressStr forKey:@"address"];
                    
                    [dict setObject:birthday.length != 0 ? birthday : @"" forKey:@"birthday"];
                    
                    [dict setObject:jobtitle.length != 0 ? jobtitle : @"" forKey:@"job_title"];
                    
                    [dict setObject:nickname.length != 0 ? nickname : @"" forKey:@"nickname"];
                    
                    [dict setObject:note.length != 0 ? note : @"" forKey:@"note"];
                    
                    [dict setObject:@"" forKey:@"create_time"];
                    
                    [dict setObject:@"" forKey:@"modify_time"];
                    
                    [contacts addObject:dict];
                    
                    
                }];
            }
            
            block(contacts);
        }];
        
    }else{//没有权限
        
        block(contacts);
    }
}

//ios 9以后查看是否有权限读取通讯录

+ (void)checkAddressBookIOS9AfterAuthorization:(void (^)(bool isAuthorized))block

{

CNContactStore *addressBook = [[CNContactStore alloc]init];

CNAuthorizationStatus authStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];;

if (authStatus != CNAuthorizationStatusAuthorized){

[addressBook requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {

dispatch_async(dispatch_get_main_queue(), ^{

if (error){

NSLog(@"ios9以后Error: %@",error);

if (error.code == 100) {//ios 9 以后第一次被用户拒绝访问之后就走 error 的方法

block(NO);

}

}else if (!granted){

block(NO);

}else{

block(YES);

}

});

}];

}else{

block(YES);

}

}

最后添加一个选择联系人的方法,调用系统的UI框架
ios9 之前的

#import <AddressBookUI/ABPeoplePickerNavigationController.h>

#import <AddressBook/ABPerson.h>

#import <AddressBookUI/ABPersonViewController.h>

和ios9 以后的

#import <Contacts/Contacts.h>

#import <ContactsUI/ContactsUI.h>

遵循代理

//第一个是 ios9以前的,第二个 ios9以后的
<ABPeoplePickerNavigationControllerDelegate,CNContactPickerDelegate>
if (IOS_VERSION_9_OR_AFTER) {//ios 9 之后

[Factory checkAddressBookIOS9AfterAuthorization:^(bool isAuthorized) {

if (isAuthorized) {

CNContactPickerViewController *contact = [[CNContactPickerViewController alloc]init];

contact.delegate = self;

[self presentViewController:contact animated:YES completion:nil];

}else{

[self alertControllerToSetup];//这里弹出提示让用户选择跳转到本程序的设置,打开通讯录

//[[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

}

}];

}else {

[Factory CheckAddressBookIOS9BeforeAuthorization:^(bool isAuthorized) {

if (isAuthorized) {

ABPeoplePickerNavigationController *nav = [[ABPeoplePickerNavigationController alloc] init];

nav.peoplePickerDelegate = self;

[self presentViewController:nav animated:YES completion:nil];

}else{

[self alertControllerToSetup];

}

}];

}
//实现代理方法

#pragma mark ABPeoplePickerNavigationControllerDelegate

//取消选择

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker

{

[peoplePicker dismissViewControllerAnimated:YES completion:nil];

}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person

{

CFTypeRef abName = ABRecordCopyValue(person, kABPersonFirstNameProperty);

CFTypeRef abLastName = ABRecordCopyValue(person, kABPersonLastNameProperty);

CFStringRef abFullName = ABRecordCopyCompositeName(person);

NSString *nameString = (__bridge NSString *)abName;

NSString *lastNameString = (__bridge NSString *)abLastName;

if ((__bridge id)abFullName != nil) {

nameString = (__bridge NSString *)abFullName;

} else {

if ((__bridge id)abLastName != nil)

{

nameString = [NSString stringWithFormat:@"%@ %@", nameString, lastNameString];

}

}

NSMutableArray * phoneArr = [[NSMutableArray alloc]init];

ABMultiValueRef phones= ABRecordCopyValue(person, kABPersonPhoneProperty);

for (NSInteger j = 0; j < ABMultiValueGetCount(phones); j++) {

[phoneArr addObject:(__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, j))];

}

if(nameString.length != 0){

self.nameTF.text =  nameString ;

}

if (phoneArr.count != 0) {

NSString *firstPhone = [phoneArr firstObject];

if ([firstPhone rangeOfString:@"-"].location != NSNotFound) {

firstPhone  = [firstPhone stringByReplacingOccurrencesOfString:@"-" withString:@""];

}

self.contactPhoneTF.text = firstPhone;

}

[peoplePicker dismissViewControllerAnimated:YES completion:nil];

}
#pragma mark  CNContactPickerDelegate

//取消

- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker

{

[picker dismissViewControllerAnimated:YES completion:nil];

}

//选中与取消选中时调用的方法

- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact

{

NSString * givenName = contact.givenName;

NSString * familyName = contact.familyName;

NSString *nameString = [NSString stringWithFormat:@"%@ %@",familyName,givenName];

NSMutableArray *phoneArray = [NSMutableArray array];

NSArray * tmpArr = contact.phoneNumbers;

for (CNLabeledValue * labelValue in tmpArr) {

CNPhoneNumber * number = labelValue.value;

[phoneArray addObject:number.stringValue];

}

self.nameTF.text = nameString;

if (phoneArray.count != 0) {

NSString *firstPhone = [phoneArray firstObject];

if ([firstPhone rangeOfString:@"-"].location != NSNotFound) {

firstPhone  = [firstPhone stringByReplacingOccurrencesOfString:@"-" withString:@""];

}

self.contactPhoneTF.text = firstPhone;

}

[picker dismissViewControllerAnimated:YES completion:nil];

}

感谢你能看到最后,Demo再次双手奉上我是Demo传送门

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335

推荐阅读更多精彩内容