1、讀取通信錄 1)、9.0以前 2)、9.0以後 2、調用通信錄UI 1)、9.0以前 2)、9.0以後 3、參考 0、寫在前面 plist 需要設置隱私許可權 Privacy - Contacts Usage Description : 請求訪問通訊錄(自定義) 1、讀取通信錄 1)、9.0以前 ...
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 room NSLog(@"個人"); } //獲取創建當前聯繫人的時間 註意是NSDate NSDate *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++) { //獲取電話Label NSString *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 Label NSString* 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++) { //獲取電話Label NSString * 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 Label NSString* 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 Label NSString* 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.0 CNContactBirthdayKey, 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); } // 獲取對方IM NSArray *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