1.获取访问授权
- <pre name="code" class="objc">#import "AppDelegate.h"
- #import <AddressBook/AddressBook.h>
- @interface AppDelegate ()
- @end
- @implementation AppDelegate
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
- //1.获取授权状态
- ABAuthorizationStatus type = ABAddressBookGetAuthorizationStatus();
- //授权申请
- if (type == kABAuthorizationStatusNotDetermined) {
- ABAddressBookRef book = ABAddressBookCreateWithOptions(NULL, NULL);
- ABAddressBookRequestAccessWithCompletion(book, ^(bool granted, CFErrorRef error) {
- if (granted) {
- NSLog(@"授权允许");
- }else{
- NSLog(@"授权拒绝");
- }
- });
- //释放book
- CFRelease(book);
- }
- return YES;
- }
2.RH导入RHAddressBook框架
RHAddressBook框架地址: https://github.com/heardrwt/RHAddressBook
3.获取联系人信息
- #import "ViewController.h"
- #import "AddressBook.h"
- @interface ViewController ()
- @end
- @implementation ViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- }
- - (void)didReceiveMemoryWarning {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
- //创建通讯录对象
- RHAddressBook* book = [[RHAddressBook alloc] init];
- //获取通讯录所有人员
- NSArray* people = book.people;
- for (RHPerson *p in people) {
- //获取人员的firstName
- NSString* firstName = p.firstName;
- //获取人员的lastName
- NSString* lastName = p.lastName;
- //获取该人员的号码(号码有多个,所以用RHMultiValue)
- RHMultiValue* phoneNumbers = p.phoneNumbers;
- NSUInteger phoneNumberCount = phoneNumbers.count;
- for (int i = 0; i < phoneNumberCount; i++) {
- //遍历每个号码中的label(比如:手机 家庭 公司)
- NSString* label = [phoneNumbers labelAtIndex:i];
- //遍历出号码
- NSString* nember = [phoneNumbers valueAtIndex:i];
- NSLog(@"%@, %@ ,%@,%@",firstName,lastName,label,nember);
- }
- }
- }
- @end
4.注意点
如果你导入RHAddressBook 框架报错,是应为框架中pch文件包含了
#import
"RHARCSupport.h" ,所以你包把这个头文件包含到你自己项目的pch文件中. 如果用的是xcode6,请参考xcode6中如何创建pch文件