你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> 詳解iOS獲得通信錄的4種方法

詳解iOS獲得通信錄的4種方法

編輯:IOS開發綜合

本文實例為年夜家分享了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, kABPersonFirstNamePh.neticProperty));

  //獲得以後接洽人的姓氏拼音
  NSString *lastNamePhoneic=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonLastNamePh.neticProperty));

  //獲得以後接洽人的中央名拼音
  NSString *middleNamePhoneic=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonMiddleNamePh.neticProperty));

  //獲得以後接洽人的公司
  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

運轉後果:

這裡寫圖片描述

以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐本站。

【詳解iOS獲得通信錄的4種方法】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved