获取通讯录大体分两大种、四小种,两大种分别是基于address框架和contacts框架开发的,四小种就是这两大种分别的有UI和无UI。
但是address框架在iOS9之后就被弃用了,虽然还可以用,但是毕竟掌握新技术才是正道。下面我就把这几种的代码贴上来,供大家参考。
一、使用AddressBook.framework框架
包含框架
#import
#import
集成代理 ABPeoplePickerNavigationControllerDelegate
1、使用UI界面
- (IBAction)addressYes:(id)sender {
ABPeoplePickerNavigationController * peoplePickerNav = [ABPeoplePickerNavigationController new];
peoplePickerNav.peoplePickerDelegate=self;
[selfpresentViewController:peoplePickerNav animated:YEScompletion:nil];
}
//===========address//- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person {//// NSLog(@"选中了person,%@",person);//}
-(void)peoplePickerNavigationController(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
NSLog(@"选中了属性,property:%d,identifier:%d",property,identifier);
}
2、界面无UI
// address框架无UI
- (IBAction)addressNo:(id)sender {
//这个变量用于记录授权是否成功,即用户是否允许我们访问通讯录
int__block tip =0;
//声明一个通讯簿的引用
ABAddressBookRef addBook =nil;
//创建通讯簿的引用
addBook = ABAddressBookCreateWithOptions(NULL,NULL);
//创建一个出事信号量为0的信号
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
//申请访问权限
ABAddressBookRequestAccessWithCompletion(addBook, ^(boolgreanted, CFErrorRef error) {
//greanted为YES是表示用户允许,否则为不允许
if(!greanted) {
tip =1;
}
//发送一次信号
dispatch_semaphore_signal(sema);
});
//等待信号触发
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);if(tip) {
//做一个友好的提示
UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"温馨提示"message:@"请您设置允许APP访问您的通讯录\nSettings>General>Privacy"delegate:selfcancelButtonTitle:@"确定"otherButtonTitles:nil,nil];
[alart show];return;
}
//获取所有联系人的数组
CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addBook);
//获取联系人总数
CFIndex number = ABAddressBookGetPersonCount(addBook);
//进行遍历
for(inti =0; i < number; i++) {
//获取联系人对象的引用
ABRecordRef people = CFArrayGetValueAtIndex(allLinkPeople, i);
//获取当前联系人名字
NSString* firstName = (__bridgeNSString*)(ABRecordCopyValue(people, kABPersonFirstNameProperty));
//获取当前联系人姓氏
NSString* lastName=(__bridgeNSString*)(ABRecordCopyValue(people, kABPersonLastNameProperty));
//获取当前联系人的名字拼音
NSString* firstNamePhoneic=(__bridgeNSString*)(ABRecordCopyValue(people, kABPersonFirstNamePhoneticProperty));
//获取当前联系人的备注
NSString* notes = (__bridgeNSString*)(ABRecordCopyValue(people, kABPersonNoteProperty));
//获取当前联系人的电话 数组
NSMutableArray* phoneArr = [[NSMutableArrayalloc]init];
ABMultiValueRef phones= ABRecordCopyValue(people, kABPersonPhoneProperty);for(NSIntegerj =0; j < ABMultiValueGetCount(phones); j++) {
[phoneArr addObject:(__bridgeNSString*)(ABMultiValueCopyValueAtIndex(phones, j))];
}
//获取当前联系人头像图片
NSData * userImage=(__bridge NSData*)(ABPersonCopyImageData(people));NSLog(@"firstName:%@,lastName:%@,firstNamePhoneic:%@,notes:%@,phoneArr:%@,userImage:%@",firstName,lastName,firstNamePhoneic,notes,phoneArr,userImage);
}
}
二、Contacts框架
包含框架
#import
#import
集成代理 CNContactPickerDelegate
代码如下 TKAddressBook *addressBook为数据模型,self.listContacts为承载模型的可变数组。
[self.listContacts removeAllObjects];
CNContactStore *store = [[CNContactStore alloc] init];
NSArray *typeArray = @[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey,CNContactOrganizationNameKey,CNContactEmailAddressesKey,CNContactPostalAddressesKey,CNContactInstantMessageAddressesKey];
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:typeArray];
//遍历所有的联系人
NSMutableDictionary *addressBookDict = [NSMutableDictionary dictionary];
[store enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
NSArray *phones = contact.phoneNumbers;
for (int i = 0; i < phones.count; i++) {
TKAddressBook *addressBook = [[TKAddressBook alloc] init];
NSString *firstName = contact.givenName;
NSString *lastName = contact.familyName;
if ([Tool isBlankString:firstName]) {
firstName = @"";
}
if ([Tool isBlankString:lastName]) {
lastName = @"";
}
//姓名
addressBook.name = [NSString stringWithFormat:@"%@%@",lastName,firstName];
CNLabeledValue *phone = phones[i];
CNPhoneNumber *phoneNum = phone.value;
NSString *num = phoneNum.stringValue;
num = [num stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
num = [num stringByReplacingOccurrencesOfString:@"\r" withString:@""];
num = [num stringByReplacingOccurrencesOfString:@"\n" withString:@""];
num = [num stringByReplacingOccurrencesOfString:@"\t" withString:@""];
num = [num stringByReplacingOccurrencesOfString:@"+86" withString:@""];
num = [num stringByReplacingOccurrencesOfString:@"-" withString:@""];
num = [num stringByReplacingOccurrencesOfString:@" " withString:@""];
addressBook.mobileNo = [NSString stringWithFormat:@"%@",num];
//公司
addressBook.company = contact.organizationName;
NSMutableString *str = [[NSMutableString alloc]init];;
//电子邮箱
for (int i = 0; i < contact.emailAddresses.count; i++) {
CNLabeledValue *email = contact.emailAddresses[i];
if (i == 0) {
[str appendString:[NSString stringWithFormat:@"%@",email.value]];
}else if(i > 0 &&i < contact.emailAddresses.count - 1){
[str appendString:[NSString stringWithFormat:@",%@",email.value]];
}
}
addressBook.emailArr = str;
//地址
NSString *addressStr = [[NSString alloc]init];
for (int i = 0; i < contact.postalAddresses.count; i++) {
CNLabeledValue *address = contact.postalAddresses[0];
CNPostalAddress *model = address.value;
addressStr = [NSString stringWithFormat:@"%@%@%@%@%@",model.country,model.state,model.city,model.subLocality,model.street];
}
addressStr = [addressStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
addressStr = [addressStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
addressStr = [addressStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
addressStr = [addressStr stringByReplacingOccurrencesOfString:@"\t" withString:@""];
addressBook.address = addressStr;
[self.listContacts addObject:addressBook];
NSString *firstLetterString = [self getFirstLetterFromString:addressBook.name];
if (addressBookDict[firstLetterString]){
[addressBookDict[firstLetterString] addObject:addressBook];
}else{
//创建新发可变数组存储该首字母对应的联系人模型
NSMutableArray *arrGroupNames = [NSMutableArray arrayWithObject:addressBook];
//将首字母-姓名数组作为key-value加入到字典中
[addressBookDict setObject:arrGroupNames forKey:firstLetterString];
}
self.tableDic = addressBookDict;
}
}];
TKAddressBook *addressBook模型参数如下
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *emailArr;
@property (strong, nonatomic) NSString *mobileNo;
@property (strong, nonatomic) NSString *company; //公司
@property (strong, nonatomic) NSString *address;