// 还是导入

#import <AddressBook/AddressBook.h>


- (void)fetchAddressBookBeforeIOS9{
ABAddressBookRef addressBook = ABAddressBookCreate();
//用户授权
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {//首次访问通讯录
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
if (!error) {
if (granted) {//允许
NSArray *contacts = [self fetchContactWithAddressBook:addressBook];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"contacts:%@", contacts);
});
}else{//拒绝
}
}else{
NSLog(@"错误!");
}
});
}else{//非首次访问通讯录
NSArray *contacts = [self fetchContactWithAddressBook:addressBook];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"contacts:%@", contacts);
});
}
} - (NSMutableArray *)fetchContactWithAddressBook:(ABAddressBookRef)addressBook{
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {////有权限访问
//获取联系人数组
NSArray *array = (__bridge NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSMutableArray *contacts = [NSMutableArray array];
for (int i = 0; i < array.count; i++) {
//获取联系人
ABRecordRef people = CFArrayGetValueAtIndex((__bridge ABRecordRef)array, i);
//获取联系人详细信息,如:姓名,电话,住址等信息
NSString *firstName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonFirstNameProperty);
NSString *lastName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonLastNameProperty);
ABMutableMultiValueRef *phoneNumRef = ABRecordCopyValue(people, kABPersonPhoneProperty);
NSString *phoneNumber = ((__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(phoneNumRef)).lastObject;
[contacts addObject:@{@"name": [firstName stringByAppendingString:lastName], @"phoneNumber": phoneNumber}];
}
return contacts;
}else{//无权限访问
NSLog(@"无权限访问通讯录");
return nil;
}
}
05-02 03:25