詳解iOS擷取通訊錄的4種方式_IOS

來源:互聯網
上載者:User

本文執行個體為大家分享了iOS擷取通訊錄的4種方式,供大家參考,具體內容如下

使用情境

一些App通過手機號碼來推薦好友,如 微博、支付寶

首先用戶端會擷取通訊錄中的所有手機號然後將這些手機號提交到App伺服器中,伺服器會尋找每個手機號對應的App帳號如QQ號碼返回到用戶端,然後用戶端根據伺服器返回的帳號列表來推薦好友。

擷取連絡人方式

方案一:AddressBookUI.framework架構

提供了連絡人清單介面、連絡人詳情介面、新增連絡人...介面等
一般用於選擇連絡人

方案二:AddressBook.framework架構:
沒有提供UI介面,需要自己搭建連絡人介面
純C語言的API, 僅僅是獲得連絡人資料
大部分資料類型是Core Foundation
從iOS6 開始,需要得到使用者的授權才能訪問通訊錄

方案三:第三方架構:RHAddressBook
對 AddressBook.framework 進行封裝

方案四:iOS9.0最新通訊錄架構
ContactsUI.framework : 方案1的替代品,特點: 物件導向,使用簡單,有介面
Contacts.framework: 方案2的替代品, 特點:物件導向,使用簡單,五介面

方案一:AddressBookUI.framework

實現步驟:

1.建立選擇連絡人的控制器
2.設定代理:用來接收使用者選擇的連絡人資訊
3.彈出連絡人控制器
4.實現代理方法
5.在對應的代理方法中擷取連絡人資訊

AddressBook.frame實現步驟:

1.請求授權
2.判斷授權狀態如果已授權則繼續,如果未授權則提示使用者
3.建立通訊錄對象
4.從通訊錄中擷取所有的連絡人
5.遍曆所有的連絡人
6.釋放不再使用的對象

AddreesBook.framework具體實現:

1. AppDelegate 應用啟動時請求授權

#import "AppDelegate.h"#import <AddressBook/AddressBook.h>@interface AppDelegate ()@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. [self requestAuthorizationAddressBook]; return YES;}- (void)requestAuthorizationAddressBook { // 判斷是否授權 ABAuthorizationStatus authorizationStatus = ABAddressBookGetAuthorizationStatus(); if (authorizationStatus == kABAuthorizationStatusNotDetermined) {  // 請求授權  ABAddressBookRef addressBookRef = ABAddressBookCreate();  ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {   if (granted) { // 授權成功   } else {  // 授權失敗    NSLog(@"授權失敗!");   }  }); }}@end

2. iOS10 需要在Info.plist配置NSContactsUsageDescription

<key>NSContactsUsageDescription</key><string>請求訪問通訊錄</string> 

3. ViewController

#import "ViewController.h"#import <AddressBook/AddressBook.h>@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad];}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { // 1. 判讀授權 ABAuthorizationStatus authorizationStatus = ABAddressBookGetAuthorizationStatus(); if (authorizationStatus != kABAuthorizationStatusAuthorized) {  NSLog(@"沒有授權");  return; } // 2. 擷取所有連絡人 ABAddressBookRef addressBookRef = ABAddressBookCreate(); CFArrayRef arrayRef = ABAddressBookCopyArrayOfAllPeople(addressBookRef); long count = CFArrayGetCount(arrayRef); for (int i = 0; i < count; i++) {  //擷取連絡人對象的引用  ABRecordRef people = CFArrayGetValueAtIndex(arrayRef, i);  //擷取當前連絡人名字  NSString *firstName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty));  //擷取當前連絡人姓氏  NSString *lastName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonLastNameProperty));  NSLog(@"--------------------------------------------------");  NSLog(@"firstName=%@, lastName=%@", firstName, lastName);  //擷取當前連絡人的電話 數組  NSMutaleArray *phoneArray = [[NSMutableArray alloc]init];  ABMultiValueRef phones = ABRecordCopyValue(people, kABPersonPhoneProperty);  for (NSInteger j=0; j<ABMultiValueGetCount(phones); j++) {   NSString *phone = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, j));   NSLog(@"phone=%@", phone);   [phoneArray addObject:phone];  }  //擷取當前連絡人的郵箱 注意是數組  NSMutableArray *emailArray = [[NSMutableArray alloc]init];  ABMultiValueRef emails= ABRecordCopyValue(people, kABPersonEmailProperty);  for (NSInteger j=0; j<ABMultiValueGetCount(emails); j++) {   NSString *email = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(emails, j));   NSLog(@"email=%@", email);   [emailArray addObject:email];  }//擷取當前連絡人中間名  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));  //擷取當前連絡人的生日  NSString *birthday=(__bridge NSDate*)(ABRecordCopyValue(people, kABPersonBirthdayProperty));  //擷取當前連絡人的備忘  NSString *notes=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonNoteProperty));  //擷取建立當前連絡人的時間 注意是NSDate  NSDate *creatTime=(__bridge NSDate*)(ABRecordCopyValue(people, kABPersonCreationDateProperty));  //擷取最近修改當前連絡人的時間  NSDate *alterTime=(__bridge NSDate*)(ABRecordCopyValue(people, kABPersonModificationDateProperty));  //擷取地址  ABMultiValueRef address = ABRecordCopyValue(people, kABPersonAddressProperty);  for (int j=0; j<ABMultiValueGetCount(address); j++) {   //地址類型   NSString *type = (__bridge NSString *)(ABMultiValueCopyLabelAtIndex(address, j));   NSDictionary * tempDic = (__bridge NSDictionary *)(ABMultiValueCopyValueAtIndex(address, j));   //地址字串,可以按需求格式化   NSString *adress = [NSString stringWithFormat:@"國家:%@\n省:%@\n市:%@\n街道:%@\n郵編:%@",[temDic valueForKey:(NSString*)kABPersonAddressCountryKey],[tempDic valueForKey:(NSString*)kABPersonAddressStateKey],[tempDic valueForKey:(NSString*)kABPersonAddressCityKey],[tempDic valueForKey:(NSString*)kABPersonAddressStreetKey],[tempDic valueForKey:(NSString*)kABPersonAddressZIPKey]];  }  //擷取當前連絡人頭像圖片  NSData *userImage=(__bridge NSData*)(ABPersonCopyImageData(people));  //擷取當前連絡人紀念日  NSMutableArray *dateArr = [[NSMutableArray alloc]init];  ABMultiValueRef dates= ABRecordCopyValue(people, kABPersonDateProperty);  for (NSInteger j=0; j<ABMultiValueGetCount(dates); j++) {   //擷取紀念日日期   NSDate *data =(__bridge NSDate*)(ABMultiValueCopyValueAtIndex(dates, j));   //擷取紀念日名稱   NSString *str =(__bridge NSString*)(ABMultiValueCopyLabelAtIndex(dates, j));   NSDictionary *tempDic = [NSDictionary dictionaryWithObject:data forKey:str];   [dateArr addObject:tempDic];  } }}@end

4. 運行結果

第三方架構:RHAddressBook

https://github.com/heardrwt/RHAddressBook

該架構使用的MRC來管理記憶體的,如果直接將原始碼拖入進去需要為每個檔案設定編譯標記:-fno-objc-arc, 設定完還會報錯,該項目使用的一些方法過於古老,很多都不支援了,所以這種方式不採用; 可以將該項目打成靜態庫的方式;也可以直接將項目拖入到自己的工程中作為一個依賴

1.直接將RHAddressBook.xcodeproj拖入到工程中

2.添加Target Dependencies和Link Binary With Libraries

3.Build Settings—> Other Linker Flags : -ObjC

用於解決系統分類找不到方法的錯誤

4.iOS10 需要在Info.plist配置NSContactsUsageDescription

<key>NSContactsUsageDescription</key><string>請求訪問通訊錄</string>  

App啟動時請求授權訪問通訊錄

#import "AppDelegate.h"#import <RHAddressBook/RHAddressBook.h>@interface AppDelegate ()@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  // Override point for customization after application launch.  [self requestAuthorizationForAddressBook];  return YES;}- (void)requestAuthorizationForAddressBook {  RHAddressBook *ab = [[RHAddressBook alloc] init];  if ([RHAddressBook authorizationStatus] == RHAuthorizationStatusNotDetermined){    [ab requestAuthorizationWithCompletion:^(bool granted, NSError *error) {      if (granted) {      } else {        NSLog(@"請求授權拒絕");      }    }];  }}@end

擷取所有連絡人的資訊:姓名、手機號等

#import "ViewController.h"#import <RHAddressBook/RHAddressBook.h>#import <RHAddressBook/AddressBook.h>@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {  [super viewDidLoad];}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {  RHAddressBook *addressBook = [[RHAddressBook alloc] init];  if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized){    NSLog(@"沒有授權");    return;  }  NSArray *peopleArray= addressBook.people;  for (int i = 0; i < peopleArray.count; i++) {    RHPerson *people = (RHPerson *)peopleArray[i];    NSLog(@"%@", people.name);    RHMultiStringValue *phoneNumbers = people.phoneNumbers;    for (int i = 0; i < phoneNumbers.count; i++) {      NSString* label= [phoneNumbers labelAtIndex:i];      NSString* value= [phoneNumbers valueAtIndex:i];      NSLog(@"label=%@, value=%@", label, value);    }    NSLog(@"----------------------------------------------");  }}@end

運行結果:

ContactsUI.framework

#import "ViewController.h"#import <ContactsUI/ContactsUI.h>@interface ViewController () <CNContactPickerDelegate>@end@implementation ViewController- (void)viewDidLoad {  [super viewDidLoad];  CNContactPickerViewController *contactPickerViewController = [[CNContactPickerViewController alloc] init];  contactPickerViewController.delegate = self;  [self presentViewController:contactPickerViewController animated:YES completion:nil];}// 如果實現該方法當選中連絡人時就不會再出現連絡人詳情介面, 如果需要看到連絡人詳情介面只能不實現這個方法,- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {  NSLog(@"選中某一個連絡人時調用---------------------------------");  [self printContactInfo:contact];}// 同時選中多個連絡人- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts {  for (CNContact *contact in contacts) {    NSLog(@"================================================");    [self printContactInfo:contact];  }}- (void)printContactInfo:(CNContact *)contact {  NSString *givenName = contact.givenName;  NSString *familyName = contact.familyName;  NSLog(@"givenName=%@, familyName=%@", givenName, familyName);  NSArray * phoneNumbers = contact.phoneNumbers;  for (CNLabeledValue<CNPhoneNumber*>*phone in phoneNumbers) {    NSString *label = phone.label;    CNPhoneNumber *phonNumber = (CNPhoneNumber *)phone.value;    NSLog(@"label=%@, value=%@", label, phonNumber.stringValue);  }}// 注意:如果實現該方法,上面那個方法就不能實現了,這兩個方法只能實現一個//- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {//  NSLog(@"選中某個連絡人的某個屬性時調用");//}@end

選擇單個連絡人時運行效果:

選擇多個連絡人的介面:


Contact.framework

iOS10 需要在Info.plist配置NSContactsUsageDescription

<key>NSContactsUsageDescription</key><string>請求訪問通訊錄</string>  

應用啟動時請求授權:

#import "AppDelegate.h"#import <Contacts/Contacts.h>@interface AppDelegate ()@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  // Override point for customization after application launch.  [self requestAuthorizationForAddressBook];  return YES;}- (void)requestAuthorizationForAddressBook {  CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];  if (authorizationStatus == CNAuthorizationStatusNotDetermined) {    CNContactStore *contactStore = [[CNContactStore alloc] init];    [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {      if (granted) {      } else {        NSLog(@"授權失敗, error=%@", error);      }    }];  }}@end

擷取通訊錄資訊

#import "ViewController.h"#import <Contacts/Contacts.h>@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {  [super viewDidLoad];}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {  CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];  if (authorizationStatus == CNAuthorizationStatusAuthorized) {    NSLog(@"沒有授權...");  }  // 擷取指定的欄位,並不是要擷取所有欄位,需要指定具體的欄位  NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];  CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];  CNContactStore *contactStore = [[CNContactStore alloc] init];  [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {    NSLog(@"-------------------------------------------------------");    NSString *givenName = contact.givenName;    NSString *familyName = contact.familyName;    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);    }//    *stop = YES; // 停止迴圈,相當於break;  }];}@end

運行效果:

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.