- (void)requestAuthorizationForAddressBook {
// 判断当前的授权状态是否是用户还未选择的状态
ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
if (status == kABAuthorizationStatusNotDetermined)
{
ABAddressBookRefbookRef =ABAddressBookCreate();
ABAddressBookRequestAccessWithCompletion(bookRef, ^(bool granted, CFErrorRef error) {
if(granted)
{
NSLog(@"授权成功!");
[selfgetmyAddressbook];
}
else
{
NSLog(@"授权失败!");
}
});
}else if (status == kABAuthorizationStatusAuthorized){
[self getmyAddressbook];
}else{
UIAlertView* alert = [[UIAlertViewalloc]initWithTitle:nilmessage:@"您的通讯录暂未允许访问,请去设置->隐私里面授权!"delegate:selfcancelButtonTitle:@"确定"otherButtonTitles:nil,nil];
[alertshow];
NSLog(@"您的通讯录暂未允许访问,请去设置->隐私里面授权!");
return;
}
}
- (void)getmyAddressbook {
// 创建通讯录对象
ABAddressBookRef bookRef = ABAddressBookCreate();
// 获取通讯录中所有的联系人
CFArrayRef arrayRef = ABAddressBookCopyArrayOfAllPeople(bookRef);
// 遍历所有联系人
CFIndexcount =CFArrayGetCount(arrayRef);
for(inti =0; i < count; i++)
{
ABRecordRefrecord =CFArrayGetValueAtIndex(arrayRef, i);
AddressBookData * data = [[AddressBookData alloc] init];
// 获取姓名
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty);
NSLog(@"firstName = %@, lastName = %@", firstName, lastName);
// 获取电话号码
ABMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonPhoneProperty);
CFIndexcount =ABMultiValueGetCount(multiValue);
NSMutableArray * array = [[NSMutableArray alloc] init];
for(inti =0; i < count; i ++)
{
NSString*label = (__bridge_transferNSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
NSString*phone = (__bridge_transferNSString*)ABMultiValueCopyValueAtIndex(multiValue, i);
NSLog(@"label = %@, phone = %@", label, phone);
NSString *strUrl = [phone stringByReplacingOccurrencesOfString:@"-" withString:@""]; //去掉-
[arrayaddObject:strUrl];
}
data.userMobileArray= [arraycopy];
if([NSStringisEmptyString:firstName] && [NSStringisEmptyString:lastName]) {
data.userNameStr= [arrayfirstObject];
}elseif(![NSStringisEmptyString:firstName] && [NSStringisEmptyString:lastName]){
data.userNameStr= firstName;
}
elseif([NSStringisEmptyString:firstName] && ![NSStringisEmptyString:lastName]){
data.userNameStr= lastName;
}else{
data.userNameStr= [NSStringstringWithFormat:@"%@%@",lastName,firstName];
}
[self.listArrayaddObject:data];
[self.tableViewreloadData];
CFRelease(multiValue);
}
CFRelease(bookRef);
CFRelease(arrayRef);
}