#import "ViewController.h"
// 提供联系人查询, 添加的UI界面
#import <AddressBookUI/AddressBookUI.h>
@interface ViewController () <UINavigationControllerDelegate, ABPeoplePickerNavigationControllerDelegate>
// 联系人查询控制器
@property (strong, nonatomic) ABPeoplePickerNavigationController *peoplePicker;
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 1. 创建
self.peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
// 2. 配置
// self.peoplePicker.delegate = self;
// 注意: 代理属性是peoplePickerDelegate, delegate属性是从UINavigationController继承过来的
self.peoplePicker.peoplePickerDelegate = self;
// 3. 弹出
[self presentViewController:self.peoplePicker animated:YES completion:nil];
}
#pragma mark - ABPeoplePickerNavigationControllerDelegate
// 点击了右上解的取消按钮时触发
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
NSLog(@"取消");
}
// 选中了某个联系人时触发
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person
{
// 如果实现了该代理方法, 那么不会进入联系人详情界面
NSLog(@"选中了联系人");
/*================= 获取联系人的姓名 =================*/
// ABRecordRef : 表示通讯录数据库当中的一条记录
// C 语言的方法通过以自己为方法名开头, 通常第一个参数都Ref是填自己
// person 实际上是 ABPerson, Property ID 定义在 ABPerson 里面
// 凡是create, retain, copy, 都需要手动的去Release
// CFTypeRef 是通用类型, 类似于 id
CFStringRef firstname = ABRecordCopyValue(person, kABPersonFirstNameProperty); // 名
CFStringRef lastname = ABRecordCopyValue(person, kABPersonLastNameProperty); // 姓
/*================= CoreFoundation 与 Foundation 之间的转换 =================*/
// 方式1: 直接转换, 不转移对象所有权 (负责retainCount引用计数)
// NSString *firstNameString = (__bridge NSString *)(f\irstname);
// NSLog(@"%@", firstNameString);
//
// CFRelease(firstname);
// 方式2: 将非OC转换成OC, 转移对象所有权 (ARC)
// NSString *firstNameString = CFBridgingRelease(firstname);
// 两者等价
NSString *firstNameString = (__bridge_transfer NSString *)firstname;
NSString *lastNameString = CFBridgingRelease(lastname);
NSLog(@"%@ : %@", firstNameString, lastNameString);
/*================= 获取联系人电话 =================*/
// kABPersonPhoneProperty 得到的是 ABMultiValueRef 的值
// ABMultiValueRef 可以理解成是一个包装 字典(Label - Value) 的 数组(多个电话)
ABMultiValueRef multiValue = ABRecordCopyValue(person, kABPersonPhoneProperty);
// 获取MultiValue的值的个数
CFIndex index = ABMultiValueGetCount(multiValue);
for (CFIndex i = 0; i < index; i++) {
// 获取每一个索引对应的label与value
CFStringRef label = ABMultiValueCopyLabelAtIndex(multiValue, i);
// 电话号码也是 CFStringRef
CFStringRef value = ABMultiValueCopyValueAtIndex(multiValue, i);
NSLog(@"%@ : %@", CFBridgingRelease(label), CFBridgingRelease(value));
}
CFRelease(multiValue);
}
@end
实用知识:<AddressBookUI/AddressBookUI.h>(获取手机通讯录)
最新推荐文章于 2020-10-02 15:14:41 发布