查看: 417|回复: 0

[IOS开发教程] iOS实现封装一个获取通讯录的工具类详解

发表于 2017-12-3 09:24:40

前言

本文给大家介绍了关于iOS如何封装一个获取通讯录工具类的相关内容,iOS获取通讯录一共有4个framework: AddressBook, AddressBookUI, Contacts, ContactsUI; 其中 AddressBook 和 AddressBookUI 已经被iOS9时 deprecated 了, 而推出了Contacts 和 ContactsUI 取代之. 其中 AddressBookUI 和 ContactsUI 是picker出一个界面提供选择一条联系人信息并且是不需要手动授权, AddressBook 和 Contacts 是获取全部通讯录数据并且需要手动授权.下面来一起看看详细的介绍吧。

注意:在iOS10获取通讯录权限需主动在info.plist里添加上提示信息. 不然会崩溃. 在info.plist里添加一对key和value

  • key: Privacy - Contacts Usage Description
  • value: 自由发挥, 这里随便写一句: 是否允许此App访问你的通讯录?

ContactsModel

新建两个数据模型文件来保存获取的通讯录数据

ContactsModel.h

  1. #import <Foundation/Foundation.h>
  2. @interface ContactsModel : NSObject
  3. @property (nonatomic, copy) NSString *num;
  4. @property (nonatomic, copy) NSString *name;
  5. - (instancetype)initWithName:(NSString *)name num:(NSString *)num;
  6. @end
复制代码

ContactsModel.m

  1. #import "ContactsModel.h"
  2. @implementation ContactsModel
  3. - (instancetype)initWithName:(NSString *)name num:(NSString *)num {
  4. if (self = [super init]) {
  5. self.name = name;
  6. self.num = num;
  7. }
  8. return self;
  9. }
  10. @end
复制代码

ContactsHelp

这是获取通讯录的工具类.

ContactsHelp.h

  1. #import <UIKit/UIKit.h>
  2. #import "ContactsModel.h"
  3. typedef void(^ContactBlock)(ContactsModel *contactsModel);
  4. @interface ContactsHelp : NSObject
  5. + (NSMutableArray *)getAllPhoneInfo;
  6. - (void)getOnePhoneInfoWithUI:(UIViewController *)target callBack:(ContactBlock)block;
  7. @end
复制代码

ContactsHelp.m

  1. #import "ContactsHelp.h"
  2. #import <AddressBook/AddressBook.h>
  3. #import <AddressBookUI/AddressBookUI.h>
  4. #import <Contacts/Contacts.h>
  5. #import <ContactsUI/ContactsUI.h>
  6. #define iOS9 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)
  7. @interface ContactsHelp () <CNContactPickerDelegate, ABPeoplePickerNavigationControllerDelegate>
  8. @property(nonatomic, strong) ContactsModel *contactModel;
  9. @property(nonatomic, strong) ContactBlock myBlock;
  10. @end
  11. @implementation ContactsHelp
  12. + (NSMutableArray *)getAllPhoneInfo {
  13. return iOS9 ? [self getContactsFromContacts] : [self getContactsFromAddressBook];
  14. }
  15. - (void)getOnePhoneInfoWithUI:(UIViewController *)target callBack:(void (^)(ContactsModel *))block {
  16. if (iOS9) {
  17. [self getContactsFromContactUI:target];
  18. } else {
  19. [self getContactsFromAddressBookUI:target];
  20. }
  21. self.myBlock = block;
  22. }
  23. #pragma mark - AddressBookUI
  24. - (void)getContactsFromAddressBookUI:(UIViewController *)target {
  25. ABPeoplePickerNavigationController *pickerVC = [[ABPeoplePickerNavigationController alloc] init];
  26. pickerVC.peoplePickerDelegate = self;
  27. [target presentViewController:pickerVC animated:YES completion:nil];
  28. }
  29. - (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person {
  30. ABMultiValueRef phonesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
  31. if (!phonesRef) { return; }
  32. NSString *phoneValue = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phonesRef, 0);
  33. CFStringRef lastNameRef = ABRecordCopyValue(person, kABPersonLastNameProperty);
  34. CFStringRef firstNameRef = ABRecordCopyValue(person, kABPersonFirstNameProperty);
  35. NSString *lastname = (__bridge_transfer NSString *)(lastNameRef);
  36. NSString *firstname = (__bridge_transfer NSString *)(firstNameRef);
  37. NSString *name = [NSString stringWithFormat:@"%@%@", lastname == NULL ? @"" : lastname, firstname == NULL ? @"" : firstname];
  38. NSLog(@"姓名: %@", name);
  39. ContactsModel *model = [[ContactsModel alloc] initWithName:name num:phoneValue];
  40. NSLog(@"电话号码: %@", phoneValue);
  41. CFRelease(phonesRef);
  42. if (self.myBlock) self.myBlock(model);
  43. }
  44. #pragma mark - ContactsUI
  45. - (void)getContactsFromContactUI:(UIViewController *)target {
  46. CNContactPickerViewController *pickerVC = [[CNContactPickerViewController alloc] init];
  47. pickerVC.delegate = self;
  48. [target presentViewController:pickerVC animated:YES completion:nil];
  49. }
  50. - (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
  51. NSString *name = [NSString stringWithFormat:@"%@%@", contact.familyName == NULL ? @"" : contact.familyName, contact.givenName == NULL ? @"" : contact.givenName];
  52. NSLog(@"姓名: %@", name);
  53. CNPhoneNumber *phoneNumber = [contact.phoneNumbers[0] value];
  54. ContactsModel *model = [[ContactsModel alloc] initWithName:name num:[NSString stringWithFormat:@"%@", phoneNumber.stringValue]];
  55. NSLog(@"电话号码: %@", phoneNumber.stringValue);
  56. if (self.myBlock) self.myBlock(model);
  57. }
  58. #pragma mark - AddressBook
  59. + (NSMutableArray *)getContactsFromAddressBook {
  60. ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
  61. CFErrorRef myError = NULL;
  62. ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &myError);
  63. if (myError) {
  64. [self showErrorAlert];
  65. if (addressBook) CFRelease(addressBook);
  66. return nil;
  67. }
  68. __block NSMutableArray *contactModels = [NSMutableArray array];
  69. if (status == kABAuthorizationStatusNotDetermined) { // 用户还没有决定是否授权你的程序进行访问
  70. ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
  71. if (granted) {
  72. contactModels = [self getAddressBookInfo:addressBook];
  73. } else {
  74. [self showErrorAlert];
  75. if (addressBook) CFRelease(addressBook);
  76. }
  77. });
  78. // 用户已拒绝 或 iOS设备上的家长控制或其它一些许可配置阻止程序与通讯录数据库进行交互
  79. } else if (status == kABAuthorizationStatusDenied || status == kABAuthorizationStatusRestricted) {
  80. [self showErrorAlert];
  81. if (addressBook) CFRelease(addressBook);
  82. } else if (status == kABAuthorizationStatusAuthorized) { // 用户已授权
  83. contactModels = [self getAddressBookInfo:addressBook];
  84. }
  85. return contactModels;
  86. }
  87. + (NSMutableArray *)getAddressBookInfo:(ABAddressBookRef)addressBook {
  88. CFArrayRef peopleArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
  89. NSInteger peopleCount = CFArrayGetCount(peopleArray);
  90. NSMutableArray *contactModels = [NSMutableArray array];
  91. for (int i = 0; i < peopleCount; i++) {
  92. ABRecordRef person = CFArrayGetValueAtIndex(peopleArray, i);
  93. ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
  94. if (phones) {
  95. NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
  96. NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
  97. NSString *name = [NSString stringWithFormat:@"%@%@", lastName == NULL ? @"" : lastName, firstName == NULL ? @"" : firstName];
  98. NSLog(@"姓名: %@", name);
  99. CFIndex phoneCount = ABMultiValueGetCount(phones);
  100. for (int j = 0; j < phoneCount; j++) {
  101. NSString *phoneValue = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phones, j);
  102. NSLog(@"电话号码: %@", phoneValue);
  103. ContactsModel *model = [[ContactsModel alloc] initWithName:name num:phoneValue];
  104. [contactModels addObject:model];
  105. }
  106. }
  107. CFRelease(phones);
  108. }
  109. if (addressBook) CFRelease(addressBook);
  110. if (peopleArray) CFRelease(peopleArray);
  111. return contactModels;
  112. }
  113. #pragma mark - Contacts
  114. + (NSMutableArray *)getContactsFromContacts {
  115. CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
  116. CNContactStore *store = [[CNContactStore alloc] init];
  117. __block NSMutableArray *contactModels = [NSMutableArray array];
  118. if (status == CNAuthorizationStatusNotDetermined) { // 用户还没有决定是否授权你的程序进行访问
  119. [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
  120. if (granted) {
  121. contactModels = [self getContactsInfo:store];
  122. } else {
  123. [self showErrorAlert];
  124. }
  125. }];
  126. // 用户已拒绝 或 iOS设备上的家长控制或其它一些许可配置阻止程序与通讯录数据库进行交互
  127. } else if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted) {
  128. [self showErrorAlert];
  129. } else if (status == CNAuthorizationStatusAuthorized) { // 用户已授权
  130. contactModels = [self getContactsInfo:store];
  131. }
  132. return contactModels;
  133. }
  134. + (NSMutableArray *)getContactsInfo:(CNContactStore *)store {
  135. NSArray *keys = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
  136. CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
  137. NSMutableArray *contactModels = [NSMutableArray array];
  138. [store enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
  139. NSString *name = [NSString stringWithFormat:@"%@%@", contact.familyName == NULL ? @"" : contact.familyName, contact.givenName == NULL ? @"" : contact.givenName];
  140. NSLog(@"姓名: %@", name);
  141. for (CNLabeledValue *labeledValue in contact.phoneNumbers) {
  142. CNPhoneNumber *phoneNumber = labeledValue.value;
  143. NSLog(@"电话号码: %@", phoneNumber.stringValue);
  144. ContactsModel *model = [[ContactsModel alloc] initWithName:name num:phoneNumber.stringValue];
  145. [contactModels addObject:model];
  146. }
  147. }];
  148. return contactModels;
  149. }
  150. #pragma mark - Error
  151. + (void)showErrorAlert {
  152. NSLog(@"授权失败, 请允许app访问您的通讯录, 在手机的”设置-隐私-通讯录“选项中设置允许");
  153. }
  154. @end
复制代码

使用

  1. #import "ContactsHelp.h"
  2. #import "ContactsModel.h"
  3. ...
  4. @property(nonatomic, strong) ContactsHelp *contactsHelp;
  5. ...
  6. - (IBAction)btn_getOne {
  7. self.contactsHelp = [[ContactsHelp alloc] init];
  8. [self.contactsHelp getOnePhoneInfoWithUI:self callBack:^(ContactsModel *contactModel) {
  9. NSLog(@"-----------");
  10. NSLog(@"%@", contactModel.name);
  11. NSLog(@"%@", contactModel.num);
  12. }];
  13. }
  14. - (IBAction)btn_getAll {
  15. NSMutableArray *contactModels = [ContactsHelp getAllPhoneInfo];
  16. [contactModels enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  17. ContactsModel *model = obj;
  18. NSLog(@"-----------");
  19. NSLog(@"%@", model.name);
  20. NSLog(@"%@", model.num);
  21. }];
  22. }
复制代码

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对程序员之家的支持。



回复

使用道具 举报

关闭

站长推荐上一条 /1 下一条