iOS-AddressBook通讯录
2017-07-06 本文已影响2351人
指头飞血
AddressBook.framework
1.纯C语言的API,仅仅提供联系人数据
2.没有提供UI界面展示,需要自己搭建联系人展示界面
3.里面数据类型大部分基于CoreFoundation框架
--从iOS6开始,需要得到用户的授权才能访问通讯录,因此在使用之前,需要检查用户是否已经授权
--获取通讯录状态 ABAddressBookGetAuthorizationStatus()
1.在需要的界面导入框架
//导入框架
#import <AddressBook/AddressBook.h>
2.在AppDelegate里面判断授权状态进行授权
#pragma mark 判断授权状态 进行授权
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
/**
kABAuthorizationStatusNotDetermined = 0,//不确定
kABAuthorizationStatusRestricted, //特殊原因不能访问通讯
kABAuthorizationStatusDenied, //拒绝访问
kABAuthorizationStatusAuthorized //已经授权
*/
//1 获取用户的授权状态
ABAuthorizationStatus statue = ABAddressBookGetAuthorizationStatus();
//2如果用户的授权状态是未决定的 则请求授权
if (statue == kABAuthorizationStatusNotDetermined) {
//2.1 获取用户通讯录对象
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
//2.2 请求授权
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
// 用户决定之后来到block
if (granted == YES) {
NSLog(@"用户授权成功");
}else{
NSLog(@"用户授权失败");
}
});
}
return YES;
}
3.获取联系人信息
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//判断授权状态
//1 获取用户的授权状态
ABAuthorizationStatus statue = ABAddressBookGetAuthorizationStatus();
//2 如果用户的授权状态是未决定的 则请求授权
if (statue != kABAuthorizationStatusAuthorized) return;//没有授权直接返回
//3 获取通讯录对象
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
//4 获取所有联系人记录
CFArrayRef peopleArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
//5 遍历所有联系人记录
CFIndex peopleCount = CFArrayGetCount(peopleArray);
for (CFIndex i = 0; i < peopleCount; i++) {
//5.1 获取到联系人
ABRecordRef person = CFArrayGetValueAtIndex(peopleArray, i);
//5.2 获取联系人姓名
NSString *firstName = (__bridge_transfer NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge_transfer NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSLog(@"--%@--%@",firstName,lastName);
//5.3 获取联系人的电话
ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
CFIndex phonesCount = ABMultiValueGetCount(phones);
for (CFIndex j = 0 ; j < phonesCount; j++) {
NSString *phoneLabel = (__bridge_transfer NSString *) ABMultiValueCopyLabelAtIndex(phones, j);
NSString *phoneValue = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phones, j);
NSLog(@"---%@---%@",phoneLabel,phoneValue);
}
//5.4 释放该释放的对象
CFRelease(phones);
}
//6 释放该释放的对象
CFRelease(addressBook);
CFRelease(peopleArray);
}