服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - iOS实现封装一个获取通讯录的工具类详解

iOS实现封装一个获取通讯录的工具类详解

2021-04-04 17:10hello老文 IOS

这篇文章主要给大家介绍了关于iOS如何实现封装一个获取通讯录的工具类的相关资料,这是自己平时封装的一个工具类,使用非常方便,文中给出了详细的示例代码,需要的朋友们可以参考借鉴,下面随着小编来一起学习学习吧。

前言

本文给大家介绍了关于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
2
3
4
5
6
7
8
#import <Foundation/Foundation.h>
 
@interface ContactsModel : NSObject
@property (nonatomic, copy) NSString *num;
@property (nonatomic, copy) NSString *name;
 
- (instancetype)initWithName:(NSString *)name num:(NSString *)num;
@end

ContactsModel.m

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

ContactsHelp

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

ContactsHelp.h

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

ContactsHelp.m

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

使用

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

总结

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

原文链接:http://www.jianshu.com/p/739d18a093a9

延伸 · 阅读

精彩推荐
  • IOSIOS 屏幕适配方案实现缩放window的示例代码

    IOS 屏幕适配方案实现缩放window的示例代码

    这篇文章主要介绍了IOS 屏幕适配方案实现缩放window的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要...

    xiari5772021-06-01
  • IOSiOS通过逆向理解Block的内存模型

    iOS通过逆向理解Block的内存模型

    自从对 iOS 的逆向初窥门径后,我也经常通过它来分析一些比较大的应用,参考一下这些应用中某些功能的实现。这个探索的过程乐趣多多,不仅能满足自...

    Swiftyper12832021-03-03
  • IOSiOS 雷达效果实例详解

    iOS 雷达效果实例详解

    这篇文章主要介绍了iOS 雷达效果实例详解的相关资料,需要的朋友可以参考下...

    SimpleWorld11022021-01-28
  • IOSiOS中tableview 两级cell的展开与收回的示例代码

    iOS中tableview 两级cell的展开与收回的示例代码

    本篇文章主要介绍了iOS中tableview 两级cell的展开与收回的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    J_Kang3862021-04-22
  • IOS关于iOS自适应cell行高的那些事儿

    关于iOS自适应cell行高的那些事儿

    这篇文章主要给大家介绍了关于iOS自适应cell行高的那些事儿,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    daisy6092021-05-17
  • IOSiOS布局渲染之UIView方法的调用时机详解

    iOS布局渲染之UIView方法的调用时机详解

    在你刚开始开发 iOS 应用时,最难避免或者是调试的就是和布局相关的问题,下面这篇文章主要给大家介绍了关于iOS布局渲染之UIView方法调用时机的相关资料...

    windtersharp7642021-05-04
  • IOS解析iOS开发中的FirstResponder第一响应对象

    解析iOS开发中的FirstResponder第一响应对象

    这篇文章主要介绍了解析iOS开发中的FirstResponder第一响应对象,包括View的FirstResponder的释放问题,需要的朋友可以参考下...

    一片枫叶4662020-12-25
  • IOSIOS开发之字典转字符串的实例详解

    IOS开发之字典转字符串的实例详解

    这篇文章主要介绍了IOS开发之字典转字符串的实例详解的相关资料,希望通过本文能帮助到大家,让大家掌握这样的方法,需要的朋友可以参考下...

    苦练内功5832021-04-01