獲取本機通訊錄中的內容,顯示在列表(table)中, iOS6之後,蘋果對系統中通訊錄日歷等控件的調用進行了權限控制,獲取通訊錄需加上請求權限部分的代碼
一、在工程中添加AddressBook.framework和AddressBookUI.framework
二、獲取通訊錄
1、在infterface中定義數組並在init方法中初始化
NSMutableArray *addressBookTemp; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { addressBookTemp = [NSMutableArray array]; }
新建一個繼承自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
@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);
//行數 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } //列數 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [addressBookTemp count]; }