iOS技艺之获取本机通讯录中的内容,解析通讯录源代码
iOS技巧之获取本机通讯录中的内容,解析通讯录源代码
2、定义一个model,用来存放通讯录中的各个属性
在.m文件中进行synthesize
三、显示在table中
列表效果
获取本机通讯录中的内容,显示在列表(table)中, iOS6之后,苹果对系统中通讯录日历等控件的调用进行了权限控制,获取通讯录需加上请求权限部分的代码
一、在工程中添加AddressBook.framework和AddressBookUI.framework
二、获取通讯录
1、在infterface中定义数组并在init方法中初始化
NSMutableArray *addressBookTemp; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { addressBookTemp = [NSMutableArray array]; }
2、定义一个model,用来存放通讯录中的各个属性
新建一个继承自NSObject的类,在.h中
@interface TKAddressBook : NSObject { NSInteger sectionNumber; NSInteger recordID; NSString *name; NSString *email; NSString *tel; } @property NSInteger sectionNumber; @property NSInteger recordID; @property (nonatomic, retain) NSString *name; @property (nonatomic, retain) NSString *email; @property (nonatomic, retain) NSString *tel; @end
在.m文件中进行synthesize
@implementation TKAddressBook @synthesize name, email, tel, recordID, sectionNumber; @end
3、获取联系人
在iOS6之后,获取通讯录需要获得权限
//新建一个通讯录类 ABAddressBookRef addressBooks = nil; if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) { addressBooks = ABAddressBookCreateWithOptions(NULL, NULL); //获取通讯录权限 dispatch_semaphore_t sema = dispatch_semaphore_create(0); ABAddressBookRequestAccessWithCompletion(addressBooks, ^(bool granted, CFErrorRef error){dispatch_semaphore_signal(sema);}); dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); dispatch_release(sema); } else { addressBooks = ABAddressBookCreate(); } //获取通讯录中的所有人 CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBooks);
三、显示在table中
//行数 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } //列数 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [addressBookTemp count]; }
列表效果