iOS 9 之后,苹果增加新特性的库 - ContactsUI.framework 和 Contacts.framework两个库
但是很多老项目仍然使用的是AddressBook.framework 库,下面先简要介绍老版本的访问通讯录的方式
导入 AddressBook.framework 库
#import <AddressBook/AddressBook.h>
- (void)viewDidLoad {
[super viewDidLoad];
// 1. 创建通讯录存储对象
ABAddressBookRef addressBook = ABAddressBookCreate();
// 2. 授权
/*
kABAuthorizationStatusNotDetermined = 0, // 未知
kABAuthorizationStatusRestricted, // 限制
kABAuthorizationStatusDenied, // 拒绝
kABAuthorizationStatusAuthorized // 允许
*/
if(ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// 3. 开始获取数据
// 3.1 获取所有联系人
CFArrayRef contacts = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex count = CFArrayGetCount(contacts);
for (int i = 0; i < count; i ++) {
//ABRecord : 信息(获取联系人信息)
ABRecordRef record = CFArrayGetValueAtIndex(contacts, i);
CFStringRef cfFirstName = ABRecordCopyValue(record,kABPersonFirstNameProperty);
CFStringRef cfLastName = ABRecordCopyValue(record,kABPersonLastNameProperty);
NSString *firstName = CFBridgingRelease(cfFirstName);
NSString *lastName = CFBridgingRelease(cfLastName);
NSLog(@"%@,%@",firstName,lastName);
}
CFRelease(contacts);
CFRelease(addressBook);
} else {
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
if(error == nil) {
NSLog(@"授权成功");
}
CFRelease(addressBook);
});
}
}
相关文章:https://wilddylan.github.io/2016/08/22/AddressBook-framework/
然后我们介绍一下iOS9 新特性的库
#import <ContactsUI/ContactsUI.h>
//1. 先遵循协议
@interface ViewController () <CNContactPickerDelegate>
@end
@implementation ViewController
//在点击屏幕的时候创建一个联系人选择控制器
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 1. 创建联系人选择控制器
CNContactPickerViewController *contact = [[CNContactPickerViewController alloc]init];
// 2. 设置代理
contact.delegate = self;
// 3. modal展示联系人页面
[self presentViewController: contact animated:YES completion:nil];
}
#pragma mark - CNContactPickerDelegate -
1. 选择单个联系人完成后调用(单选 ⚠️:当方法- contactPicker: didSelectContacts:被实现时,此方法被屏蔽掉)
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact;
2. 选择多个联系人完成后调用(多选 ⚠️:实现此方法,上面方法将被屏蔽)
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact*> *)contacts;
3. 当点击单个联系人进入联系人属性页面,点击某属性后调用(⚠️:如果didSelectContact 和 didSelectContactProperties 这2个代理方法没有被实现才会被调用)
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty;
4. 当选择多个联系人的属性被调用
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperties:(NSArray<CNContactProperty*> *)contactProperties;