先把Demo雙手奉上我是Demo傳送門
首先在info.plist里面添加讀取通訊錄的權(quán)限
通訊錄權(quán)限: Privacy - Contacts Usage Description 是否允許此App訪問(wèn)你的通訊錄?
然后再寫(xiě)一個(gè)宏判斷系統(tǒng)版本,這樣可以根據(jù) ios9 來(lái)判斷使用哪一種系統(tǒng)框架
#define IOS_VERSION_9_OR_AFTER (([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)? (YES):(NO))
ios 9 之前的框架----AddressBook Framework
導(dǎo)入框架AddressBook.Framework,需要UI就導(dǎo)入 AddressBookUI.Framework
導(dǎo)入頭文件#import <AddressBook/AddressBook.h>
//獲取通訊錄數(shù)組
+(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(@"請(qǐng)您設(shè)置允許APP訪問(wèn)您的通訊錄\n設(shè)置>通用>隱私");
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<ABMultiValueGetCount(phone); k++)
{
//獲取電話Label
// NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
//獲取該Label下的電話值
NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
phoneStr = [phoneStr stringByAppendingFormat:@"%@ ",personPhone];
}
NSString * note = (__bridge NSString*)(ABRecordCopyValue(people, kABPersonNoteProperty));
NSString *email = @"";
//獲取email多值
ABMultiValueRef emailRef = ABRecordCopyValue(people, kABPersonEmailProperty);
for (int x = 0; x < ABMultiValueGetCount(emailRef); x++)
{
//獲取email Label
// NSString* emailLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(emailRef, x));
//獲取email值
email = (__bridge NSString*)ABMultiValueCopyValueAtIndex(emailRef, x);
}
//讀取jobtitle工作
NSString *jobtitle = (__bridge NSString*)ABRecordCopyValue(people, kABPersonJobTitleProperty);
//讀取nickname呢稱
NSString *nickname = (__bridge NSString*)ABRecordCopyValue(people, kABPersonNicknameProperty);
NSString * organization = (__bridge NSString*)(ABRecordCopyValue(people, kABPersonOrganizationProperty));
NSDate *birthDate = (__bridge NSDate *)(ABRecordCopyValue(people, kABPersonBirthdayProperty));
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.dateFormat = @"yyyy-MM-dd";
NSString *birthday = @"";
if (birthDate) {
birthday = [dateFormatter stringFromDate:birthDate];
}
//第一次添加該條記錄的時(shí)間
NSDate *createDate = (__bridge NSDate*)ABRecordCopyValue(people, kABPersonCreationDateProperty);
NSString *createTime = @"";
if (createDate) {
createTime = [dateFormatter stringFromDate:createDate];
}
//最后一次修改該條記錄的時(shí)間
NSDate *modifyDate = (__bridge NSDate*)ABRecordCopyValue(people, kABPersonModificationDateProperty);
NSString *modifyTime = @"";
if (modifyDate) {
modifyTime = [dateFormatter stringFromDate:modifyDate];
}
//讀取地址多值
ABMultiValueRef address = ABRecordCopyValue(people, kABPersonAddressProperty);
NSString *addressStr = @"";
for(int j = 0; j < ABMultiValueGetCount(address); j++)
{
//獲取地址Label
// NSString* addressLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(address, j);
//獲取該label下的地址6屬性
NSDictionary* personaddress =(__bridge NSDictionary*) ABMultiValueCopyValueAtIndex(address, j);
NSString* country = [personaddress valueForKey:(NSString *)kABPersonAddressCountryKey];
if(country != nil)
addressStr = [addressStr stringByAppendingFormat:@"%@ ",country];
NSString* city = [personaddress valueForKey:(NSString *)kABPersonAddressCityKey];
if(city != nil)
addressStr = [addressStr stringByAppendingFormat:@"%@ ",city];
NSString* state = [personaddress valueForKey:(NSString *)kABPersonAddressStateKey];
if(state != nil)
addressStr = [addressStr stringByAppendingFormat:@"%@ ",state];
NSString* street = [personaddress valueForKey:(NSString *)kABPersonAddressStreetKey];
if(street != nil)
addressStr = [addressStr stringByAppendingFormat:@"%@ ",street];
// NSString* zip = [personaddress valueForKey:(NSString *)kABPersonAddressZIPKey];
// if(zip != nil)
// addressStr = [addressStr stringByAppendingFormat:@"郵編:%@",zip];
}
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 != nil ? 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:createTime forKey:@"create_time"];
[dict setObject:modifyTime forKey:@"modify_time"];
[peopleArray addObject:dict];
if(abName) CFRelease(abName);
if(abLastName) CFRelease(abLastName);
if(abFullName) CFRelease(abFullName);
if(people) CFRelease(people);
}
if(allLinkPeople) CFRelease(allLinkPeople);
return peopleArray;
}
//查看是否有權(quán)限讀取通訊錄
+(void)CheckAddressBookIOS9BeforeAuthorization:(void (^)(bool isAuthorized))block
{
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();
if (authStatus != kABAuthorizationStatusAuthorized)
{
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
{
dispatch_async(dispatch_get_main_queue(), ^{
if (!granted)
{
block(NO);
}
else
{
block(YES);
}
});
});
}
else{
block(YES);
}
}
ios 9之后的框架-----Contacts Framework
導(dǎo)入框架Contacts.Framework,需要UI就導(dǎo)入 ContactsUI.Framework導(dǎo)入頭文件
導(dǎo)入#import <Contacts/Contacts.h>
//ios 9 以后 使用block 返回 聯(lián)系人數(shù)組
+(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];
//這里寫(xiě)要獲取的內(nèi)容的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{//沒(méi)有權(quán)限
block(contacts);
}
}
//ios 9以后查看是否有權(quán)限讀取通訊錄
+ (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 以后第一次被用戶拒絕訪問(wèn)之后就走 error 的方法
block(NO);
}
}else if (!granted){
block(NO);
}else{
block(YES);
}
});
}];
}else{
block(YES);
}
}
最后添加一個(gè)選擇聯(lián)系人的方法,調(diào)用系統(tǒng)的UI框架
ios9 之前的
#import <AddressBookUI/ABPeoplePickerNavigationController.h>
#import <AddressBook/ABPerson.h>
#import <AddressBookUI/ABPersonViewController.h>
和ios9 以后的
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>
遵循代理
//第一個(gè)是 ios9以前的,第二個(gè) ios9以后的
<ABPeoplePickerNavigationControllerDelegate,CNContactPickerDelegate>
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];//這里彈出提示讓用戶選擇跳轉(zhuǎn)到本程序的設(shè)置蔓倍,打開(kāi)通訊錄
//[[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];
}
}];
}
//實(shí)現(xiàn)代理方法
#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];
}
//選中與取消選中時(shí)調(diào)用的方法
- (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傳送門