最近学习了iOS获取手机通讯录方式方法,现在分享给大家。希望此文章对各位有所帮助。
一、iOS 9 以前的通讯录框架
AddressBookUI框架:提供了联系人列表界面、联系人详情界面、添加联系人界面等,一般用于选择联系人。
AddressBook 框架:纯 C 语言的 API,仅仅是获得联系人数据。没有提供 UI 界面展示,需要自己搭建联系人展示界面。
二、 iOS 9 以后最新通讯录框架
ContactsUI 框架:拥有 AddressBookUI 框架的所有功能,使用起来更加的面向对象。
Contacts 框架:拥有 AddressBook框架的所有功能,不再是 C 语言的 API,使用起来非常简单。
这次主要说下iOS9以后获取手机通讯录的方法:
所需框架
#import <ContactsUI/ContactsUI.h>
遵循代理
<CNContactPickerDelegate>
1、请求授权判断
// 判断当前的授权状态
if (status != CNAuthorizationStatusAuthorized) {
UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请您设置允许APP访问您的通讯录n设置-隐私-通讯录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
return;
}
这个说下几个授权状态,和AddressBook的差不多
typedef NS_ENUM(NSInteger, CNAuthorizationStatus)
{
/*! 用户尚未就应用程序是否可以访问联系人数据做出选择。 */
CNAuthorizationStatusNotDetermined = 0,
/*! 该应用程序没有权限访问联系人数据。
*用户无法更改此应用程序的状态,可能是由于主动限制(如父母控制到位)。 */
CNAuthorizationStatusRestricted,
/*! 用户明确拒绝对应用程序的联系人数据的访问。 */
CNAuthorizationStatusDenied,
/*! 该应用程序被授权访问联系人数据。 */
CNAuthorizationStatusAuthorized
}
判断
// 判断当前的授权状态是否是用户还未选择的状态
if (status == CNAuthorizationStatusNotDetermined)
{
CNContactStore *store = [CNContactStore new];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted){
NSLog(@"授权成功!");
}else{
NSLog(@"授权失败!");
}
}];
}
2、创建通讯录控制器
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//iOS 10
// AB_DEPRECATED("Use CNContactPickerViewController from ContactsUI.framework instead")
CNContactPickerViewController * contactVc = [CNContactPickerViewController new];
contactVc.delegate = self;
[self presentViewController:contactVc animated:YES completion:nil];
}
如果在iOS10的机器上调用以前的ABPeoplePickerNavigationController老方法将直接崩溃。所以如果还是用以前的方法,则需要加判断版本判断










