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

//获取通讯录数组

+(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

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

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

导入#import

//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 

#import 

#import 

和ios9 以后的

#import 

#import 

遵循代理

//第一个是 ios9以前的,第二个 ios9以后的

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传送门

你可能感兴趣的:(ios调用通讯录以及选择联系人列表方法)