1.第一步:
第二步:
#import <AddressBook/AddressBook.h>
第三步:
if (&ABAddressBookRequestAccessWithCompletion != NULL) {
ABAddressBookRef abRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
//如果该应用从未申请过权限,申请权限
ABAddressBookRequestAccessWithCompletion(abRef, ^(bool granted, CFErrorRef error) {
//根据granted参数判断用户是否同意授予权限
if (granted) {
//查询所有,这里我们可以用来进行下一步操作
[self readContrants];
}
});
} else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
//如果权限已经被授予
//查询所有,这里我们可以用来进行下一步操作
[self readContrants];
} else {
//如果权限被收回,只能提醒用户去系统设置菜单中打开
UIAlertView *av = [[UIAlertView alloc]
initWithTitle:@"提示"
message:@"无限美丽访问系统通讯录的权限已被关闭,请到手机系统[设置]中开启权限,此项有助于为你提高审批通过率及信用额度"
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:@"OK",nil];
[av show];
}
if(abRef){
CFRelease(abRef);
}
}
}
-(void)readContrants
{
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray * myContacts = [NSArray arrayWithArray:(__bridge_transfer NSArray*)
ABAddressBookCopyArrayOfAllPeople(addressBook)];
NSLog(@"%@",myContacts);
int count=myContacts.count>=20?20:(int)myContacts.count;
for (int i=0; i<count; i++) {
ABRecordRef person =(__bridge ABRecordRef)(myContacts[i]);
//objc_unretainedPointer([myContacts objectAtIndex:i]);
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person,
kABPersonPhoneProperty);
NSString * phone= (__bridge NSString *)(ABMultiValueCopyValueAtIndex(phoneNumbers, 0));
NSLog(@"%@",phone);
ABMutableMultiValueRef firstNameMulti = ABRecordCopyValue(person, kABPersonFirstNameProperty);
ABMutableMultiValueRef middleNameMulti = ABRecordCopyValue(person, kABPersonMiddleNameProperty);
ABMutableMultiValueRef lastNameMulti = ABRecordCopyValue(person, kABPersonLastNameProperty);
NSString *firsNameString =(__bridge_transfer NSString*)firstNameMulti;
NSString *middleNameString = (__bridge_transfer NSString*)middleNameMulti;
NSString *lastNameString = (__bridge_transfer NSString*)lastNameMulti;
if (firsNameString.length==0) {
firsNameString=@"";
}
if (middleNameString.length==0) {
middleNameString=@"";
}
if (lastNameString.length==0) {
lastNameString=@"";
}
if (phone.length==0) {
phone=@"";
}
NSString *nameString = [NSString stringWithFormat:@"%@%@%@",lastNameString,middleNameString,firsNameString];
NSLog(@"%@",nameString);
NSDictionary * dic=@{@"name":nameString,@"phone":phone};
[_addressBookArray addObject:dic];
[GFDataSaver saveString:@"book" forKey:@"book"];
NSLog(@"%@",_addressBookArray);
}