iOS:通信錄(完成)(18-01-18更)

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

轉載于:https://www.cnblogs.com/leonlincq/p/8304249.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390328.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390328.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390328.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

如何在React Native和Firebase中設置Google登錄

Google sign-in is a great login feature to offer to your apps users. It makes it easier for them to create an account and sign in. Google登錄是一項出色的登錄功能&#xff0c;可為您的應用程序用戶提供。 這使他們更容易創建帳戶并登錄。 And whats even better, F…

設計模式-發布訂閱模式

這段時間在看vue的雙向綁定原理&#xff0c;知道了vue的核心三大件&#xff1a;Observer, Complie, Watcher。 Observer用于監聽屬性的變化&#xff0c;如有變動就通知 Watcher。 Compile負責解析元素節點的指令&#xff0c;如v-if&#xff0c;v-bind之類, 進行數據和回調函數的…

杜教篩--51nod1239 歐拉函數之和

求$\sum_{i1}^{n}\varphi (i)$&#xff0c;$n\leqslant 1e10$。 這里先把杜教篩的一般套路貼一下&#xff1a; 要求$S(n)\sum_{i1}^{n}f(i)$&#xff0c;而現在有一數論函數$g(i)$&#xff0c;$g(i)$的前綴和很無腦&#xff0c;且$f$和$g$的狄利克雷卷積的前綴和很無腦&#xf…

【Android Studio安裝部署系列】目錄

概述 從剛開始使用Android Studio到現在&#xff0c;下面所有目錄下的操作&#xff0c;當時習慣性的把每一個整理成一個文檔&#xff08;其實就是簡單文字描述截圖&#xff09;&#xff1b;有些地方當時是一知半解&#xff0c;現在會稍微明白一些。正好趕上現在有時間。所以就想…

修改npm全局安裝模式的路徑

修改npm全局安裝模式的路徑 在正式寫此文章之前&#xff0c;我得說一點血淚史。 剛學nodeJS不久&#xff0c;很納悶為什么全局安裝的模塊在 node安裝目錄/node_modules‘ 中沒找到&#xff01;后來仔細看了下安裝成功后的信息&#xff0c;才發現原來是自動安裝在C盤了&#xff…

javascript創建類_如何使用JavaScript創建吹氣效果

javascript創建類Have you ever wondered how you can create a realistic air blowing effect with JavaScript? Like the one shown on the evening TV shows, where multiple balls are being mixed up in a sphere-like object by leveraging air pressure? If you want …

Bootstrap 4:如何使頂部固定的Navbar保持在容器中而不拉伸?

There are many ways to make a fixed navbar stay inside a parents div container. Well go over the most straightforward one here.有很多方法可以使固定的導航欄停留在父級的div容器中。 我們將在這里介紹最簡單的方法。 Imagine you have the following code, modified…

基于SpringBoot+Mybatis+Thymeleaf商品信息管理系統

github地址&#xff1a;github.com/zaiyunduan1…,如果對你有幫助&#xff0c;歡迎Star 主要用到的技術&#xff1a; 使用maven進行項目構建使用SpringbootMybatis搭建整個系統使用Thymeleaf模板技術實現頁面靜態化使用框架Bootstrap、JQuery開發前端界面使用MySQL和MongoDB分別…

在Mac上為自己手動編譯安裝一套PHP7的開發環境

首先你得去官網下載php7 beta1的版本 這里由于我是在mac上安裝&#xff0c;所以就去下載linux相關的版本&#xff0c;地址也直接附上了php7 beta1windows版的官方也有發布詳情猛戳&#xff1a;這里 解壓安裝包&#xff0c;進入源代碼目錄 tar -zxvf php-7.0.0beta1.tar.gz cd p…

卡特蘭數 HDU2067 HDU4165 HDU1134

題目鏈接&#xff1a;https://vjudge.net/problem/HDU-2067 小兔的棋盤 Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 11800 Accepted Submission(s): 5952 Problem Description小兔的叔叔從外面旅游回來給她…

Python的用途是什么? Python編程語言有10多種編碼用途。

&#x1f44b;歡迎 (&#x1f44b; Welcome) Hi! Please take a moment to think about this question: 嗨&#xff01; 請花一點時間考慮這個問題&#xff1a; How is Python applied in real-world scenarios? Python如何在實際場景中應用&#xff1f; If you are learnin…

Publish/Subscribe

Publish/Subscribe 我們將會投遞一個消息給多個消費者&#xff0c;這種模式被稱為“publish/subscribe” 通俗的講&#xff0c;前面的是點對點隊列模型&#xff0c;現在講的是發布訂閱模型。 Exchanges producer&#xff1a;一個發送消息的用戶應用程序 queue&#xff1a;一個存…

[轉]在ROS下使用zeroconf配置多機通信

原文地址&#xff1a;http://www.corvin.cn/635.html&#xff0c;轉載主要方便隨時查閱&#xff0c;如有版權要求&#xff0c;請及時聯系。 0x00 為何需要配置ROS多機通信 眾所周知ROS是分布式系統&#xff0c;因此可以將機器人需要處理的復雜、計算量大的任務分解在多臺機器上…

python中斐波那契數列_斐波那契數列–在Python,JavaScript,C ++,Java和Swift中進行了解釋...

python中斐波那契數列by Pau Pavn通過保羅帕文(PauPavn) The Fibonacci sequence is, by definition, the integer sequence in which every number after the first two is the sum of the two preceding numbers. To simplify:根據定義&#xff0c;斐波那契數列是整數序列&a…

1583. 統計不開心的朋友

1583. 統計不開心的朋友 給你一份 n 位朋友的親近程度列表&#xff0c;其中 n 總是 偶數 。 對每位朋友 i&#xff0c;preferences[i] 包含一份 按親近程度從高到低排列 的朋友列表。換句話說&#xff0c;排在列表前面的朋友與 i 的親近程度比排在列表后面的朋友更高。每個列…

uva 247(floyd傳遞閉包)

為什么&#xff0c;逗號后面&#xff0c;還有空格........ #include <iostream> #include <cstring> #include <algorithm> #include <cstdio> #include <vector> #include <map> using namespace std; const int maxn50; int d[maxn][max…

VS Code 的常用快捷鍵和插件

注:文章摘自 風行天下一萬號 - 博客園 vs code 的常用快捷鍵 1、注釋&#xff1a; 單行注釋&#xff1a;[ctrlk,ctrlc] 或 ctrl/取消單行注釋&#xff1a;[ctrlk,ctrlu] (按下ctrl不放&#xff0c;再按k u)多行注釋&#xff1a;[altshiftA]多行注釋&#xff1a;/**2、移動行&a…

python包numpy_NumPy Python科學計算軟件包的終極指南

python包numpyNumPy (pronounced "numb pie") is one of the most important packages to grasp when you’re starting to learn Python.NumPy(讀作“麻木派”)是您開始學習Python時要掌握的最重要的軟件包之一。 The package is known for a very useful data str…

NGINX原理 之 SLAB分配機制(轉)

1 引言 眾所周知&#xff0c;操作系統使用伙伴系統管理內存&#xff0c;不僅會造成大量的內存碎片&#xff0c;同時處理效率也較低下。SLAB是一種內存管理機制&#xff0c;其擁有較高的處理效率&#xff0c;同時也有效的避免內存碎片的產生&#xff0c;其核心思想是預分配。其按…

apk之間數據共享的方式

1、四大組件之ContentProvider大法2、shareUserId3、apk均去遠端獲取配置文件&#xff08;或接口&#xff09;4、AIDL&#xff08;bindService&#xff09;5、SharePreference設置為MODE_WORLD_READABLE|MODE_WORLD_WRITEABLE模式&#xff0c;由于存在安全問題&#xff0c;已被…