1、讀取通信錄
1)、9.0以前:AddressBook
2)、9.0以后:Contacts
2、調用通信錄UI(不弄)
1)、9.0以前:AddressBookUI
2)、9.0以后:ContactsUI
3、參考
?
0、寫在前面
1)、plist 需要設置 隱私權限描述
NSContactsUsageDescription(Privacy - Contacts Usage Description) :請求訪問通訊錄(自定義)?
2)、一般應用只需要電話就夠了,不過,如果想做?壞事?大數據分析,可能還是要全讀取給后臺吧?
3)、9.0后的 Contacts 類:
3-1)、如果請求數據的數組里沒有該Key,但在 block 判斷有,會奔潰。
3-2)、請求類型key,有10.0后的,需要注意,做判斷。
4)、原生UI不打算弄了,感覺一般都是自定義UI,比如:有注冊的在上面,添加好友按鈕,沒注冊的在下面,邀請好友按鈕。
5)、有空再整理成 單例manage。?
?
1、讀取通信錄
1)、9.0以前
1-1)、頭文件
#import <AddressBook/AddressBook.h>
1-2)、判斷是否有權限
- (void)DetermineAndReadAddressBook
{// 判斷是否授權ABAuthorizationStatus authorizationStatus = ABAddressBookGetAuthorizationStatus();if (authorizationStatus == kABAuthorizationStatusNotDetermined) {// 請求授權ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error){if (granted) {// 授權成功[self readAddressBook];} else {// 授權失敗NSLog(@"提示:用戶取消授權,讀取失敗");}});}else if (authorizationStatus == kABAuthorizationStatusAuthorized){// 授權過[self readAddressBook];}else {dispatch_async(dispatch_get_main_queue(), ^{// 更新界面NSLog(@"提示:應用-通信錄 設置");});}
}
1-3)、讀取并保存模型(未做)
- (void)readAddressBook {// 獲取所有聯系人ABAddressBookRef addressBookRef = ABAddressBookCreate();// 獲取所有聯系人 數據CFArrayRef peoples = ABAddressBookCopyArrayOfAllPeople(addressBookRef);// 獲取所有聯系人 個數CFIndex peoplesCount = ABAddressBookGetPersonCount(addressBookRef);for (int i = 0; i < peoplesCount; i++) {//獲取聯系人對象的引用ABRecordRef people = CFArrayGetValueAtIndex(peoples, i);//獲取當前聯系人名字NSString *firstName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty));//獲取當前聯系人姓氏NSString *lastName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonLastNameProperty));NSLog(@"--------------------------------------------------");NSLog(@"firstName=%@, lastName=%@", firstName, lastName);//獲取當前聯系人中間名NSString *middleName=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonMiddleNameProperty));//獲取當前聯系人的名字前綴NSString *prefix=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonPrefixProperty));//獲取當前聯系人的名字后綴NSString *suffix=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonSuffixProperty));//獲取當前聯系人的昵稱NSString *nickName=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonNicknameProperty));//獲取當前聯系人的名字拼音NSString *firstNamePhoneic=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonFirstNamePhoneticProperty));//獲取當前聯系人的姓氏拼音NSString *lastNamePhoneic=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonLastNamePhoneticProperty));//獲取當前聯系人的中間名拼音NSString *middleNamePhoneic=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonMiddleNamePhoneticProperty));//獲取當前聯系人的公司NSString *organization=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonOrganizationProperty));//獲取當前聯系人的職位NSString *job=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonJobTitleProperty));//獲取當前聯系人的部門NSString *department=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonDepartmentProperty));//獲取當前聯系人的生日NSDate *birthday=(__bridge NSDate*)(ABRecordCopyValue(people, kABPersonBirthdayProperty));//獲取當前聯系人的備注NSString *notes=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonNoteProperty));//獲取當前聯系人頭像圖片NSData *userImage=(__bridge NSData*)(ABPersonCopyImageData(people));//獲取kind值CFNumberRef kindType = ABRecordCopyValue(people, kABPersonKindProperty);if (kindType == kABPersonKindOrganization) {NSLog(@"公司");} else {// it's a person, resource, or roomNSLog(@"個人");}//獲取創建當前聯系人的時間 注意是NSDateNSDate *creatTime=(__bridge NSDate*)(ABRecordCopyValue(people, kABPersonCreationDateProperty));//獲取最近修改當前聯系人的時間NSDate *alterTime=(__bridge NSDate*)(ABRecordCopyValue(people, kABPersonModificationDateProperty));//獲取當前聯系人的電話 數組NSMutableArray *phoneArray = [[NSMutableArray alloc]init];ABMultiValueRef phones = ABRecordCopyValue(people, kABPersonPhoneProperty);CFIndex phonesCount = ABMultiValueGetCount(phones);for (NSInteger j=0; j<phonesCount; j++) {//獲取電話LabelNSString *phoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phones, j));//獲取該Label下的電話值NSString *phone = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, j));NSLog(@"phone=%@", phone);[phoneArray addObject:phone];}//獲取IM多值NSMutableArray *instantMessageArray = [[NSMutableArray alloc]init];ABMultiValueRef instantMessages = ABRecordCopyValue(people, kABPersonInstantMessageProperty);CFIndex instantMessagesCount = ABMultiValueGetCount(instantMessages);for (int j = 1; j < instantMessagesCount; j++){//獲取IM LabelNSString* instantMessageLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(instantMessages, j);//獲取IM 的內容NSDictionary* instantMessageContent =(__bridge NSDictionary*)ABMultiValueCopyValueAtIndex(instantMessages, j);NSString* username = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageUsernameKey];NSString* service = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageServiceKey];}//獲取URL多值NSMutableArray *urlArray = [[NSMutableArray alloc]init];ABMultiValueRef urls = ABRecordCopyValue(people, kABPersonURLProperty);CFIndex urlsCount = ABMultiValueGetCount(urls);for (int j = 0; j < urlsCount; j++){//獲取電話LabelNSString * urlLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(urls, j));//獲取該Label下的電話值NSString * urlContent = (__bridge NSString*)ABMultiValueCopyValueAtIndex(urls,j);}//獲取當前聯系人的郵箱 注意是數組NSMutableArray *emailArray = [[NSMutableArray alloc]init];ABMultiValueRef emails= ABRecordCopyValue(people, kABPersonEmailProperty);CFIndex emailsCount = ABMultiValueGetCount(emails);for (NSInteger j=0; j< emailsCount; j++) {//獲取email LabelNSString* emailLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(emails, j));//獲取email值NSString *email = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(emails, j));NSLog(@"email=%@", email);[emailArray addObject:email];}//獲取地址 注意是數組NSMutableArray *addressArray = [[NSMutableArray alloc]init];ABMultiValueRef addresss = ABRecordCopyValue(people, kABPersonAddressProperty);CFIndex addresssCount = ABMultiValueGetCount(addresss);for (int j=0; j<addresssCount; j++) {// 地址類型NSString *addressLabel = (__bridge NSString *)(ABMultiValueCopyLabelAtIndex(addresss, j));NSDictionary * personaddress = (__bridge NSDictionary *)(ABMultiValueCopyValueAtIndex(addresss, j));// 獲取地址NSString* country = [personaddress valueForKey:(NSString *)kABPersonAddressCountryKey];NSString* state = [personaddress valueForKey:(NSString *)kABPersonAddressStateKey];NSString* city = [personaddress valueForKey:(NSString *)kABPersonAddressCityKey];NSString* street = [personaddress valueForKey:(NSString *)kABPersonAddressStreetKey];NSString* zip = [personaddress valueForKey:(NSString *)kABPersonAddressZIPKey];NSString* coutntrycode = [personaddress valueForKey:(NSString *)kABPersonAddressCountryCodeKey];//地址字符串,可以按需求格式化NSString *adress = [NSString stringWithFormat:@"國家:%@\n省:%@\n市:%@\n街道:%@\n郵編:%@",country,state,city,street,zip];}//獲取當前聯系人紀念日NSMutableArray *dateArr = [[NSMutableArray alloc]init];ABMultiValueRef dates= ABRecordCopyValue(people, kABPersonDateProperty);CFIndex datesCount = ABMultiValueGetCount(dates);for (NSInteger j=0; j<datesCount; j++) {//獲取dates LabelNSString* dateLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(dates, j));//獲取紀念日日期NSDate *date =(__bridge NSDate*)(ABMultiValueCopyValueAtIndex(dates, j));//獲取紀念日名稱NSString *str =(__bridge NSString*)(ABMultiValueCopyLabelAtIndex(dates, j));NSDictionary *tempDic = [NSDictionary dictionaryWithObject:date forKey:str];[dateArr addObject:tempDic];}}
}
?
? 2)、9.0以后
2-1)、頭文件
#import <Contacts/Contacts.h>
2-2)、判斷是否有權限
- (void)DetermineAndReadAddressBook
{// 判斷是否授權CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];if (authorizationStatus == CNAuthorizationStatusNotDetermined) {CNContactStore *contactStore = [[CNContactStore alloc] init];[contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {if (granted) {// 授權成功[self readAddressBook];} else {// 授權失敗NSLog(@"提示:用戶取消授權,讀取失敗");}}];}else if (authorizationStatus == CNAuthorizationStatusAuthorized){// 授權過[self readAddressBook];}else {dispatch_async(dispatch_get_main_queue(), ^{// 更新界面NSLog(@"提示:應用-通信錄 設置");});}
}
2-3)、讀取并保存模型(未做)
- (void)readAddressBook {// 獲取指定的字段,如果這里不列出,在下面block讀取,會奔潰。注意,有一個是10.0以后的。NSArray *keysToFetch = @[CNContactNamePrefixKey,CNContactGivenNameKey,CNContactMiddleNameKey,CNContactFamilyNameKey,CNContactPreviousFamilyNameKey,CNContactNameSuffixKey,CNContactNicknameKey,CNContactOrganizationNameKey,CNContactDepartmentNameKey,CNContactJobTitleKey,CNContactPhoneticGivenNameKey,CNContactPhoneticMiddleNameKey,CNContactPhoneticFamilyNameKey,CNContactPhoneticOrganizationNameKey, // 10.0CNContactBirthdayKey,CNContactNonGregorianBirthdayKey,CNContactNoteKey,CNContactImageDataKey,CNContactThumbnailImageDataKey,CNContactImageDataAvailableKey,CNContactTypeKey,CNContactPhoneNumbersKey,CNContactEmailAddressesKey,CNContactPostalAddressesKey,CNContactDatesKey,CNContactUrlAddressesKey,CNContactRelationsKey,CNContactSocialProfilesKey,CNContactInstantMessageAddressesKey];CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];CNContactStore *contactStore = [[CNContactStore alloc] init];[contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {// 獲取名字NSString *givenName = contact.givenName;NSString *familyName = contact.familyName;NSLog(@"-------------------------------------------------------");NSLog(@"givenName=%@, familyName=%@", givenName, familyName);// 獲取電話NSArray *phoneNumbers = contact.phoneNumbers;for (CNLabeledValue *labelValue in phoneNumbers) {NSString *label = labelValue.label;CNPhoneNumber *phoneNumber = labelValue.value;NSLog(@"label=%@, phone=%@", label, phoneNumber.stringValue);}// 獲取對方IMNSArray *ims = contact.instantMessageAddresses;for (CNLabeledValue *labelValue in ims) {NSString *label = labelValue.label;CNInstantMessageAddress *adds = labelValue.value;NSLog(@"label=%@, add.username=%@,add.service=%@", label, adds.username , adds.service);}// *stop = YES; // 停止循環,相當于break;}];
}
?
?
?
3、參考
《iOS的通訊錄開發》 --千煌89 簡書
《iOS 獲取通訊錄的4種方式詳解》 --vbirdbest CSDN