由於ios系統對用戶隱私的控制,第三方應用程序只能通過蘋果官方接口調用系統通訊錄,不能像android那樣直接操作通訊錄數據庫。
一般地,使用系統自帶通訊錄的方法有兩種,一種是直接將整個通訊錄引入到應用程序,另一種是逐條讀取通訊錄中的每一條聯系人信息。下面我們就一一詳解。
1 直接引用整個通訊錄
使用的類:ABPeoplePickerNavigationController
方法:
在LocalAddressBookController.h文件中 #import <UIKit/UIKit.h> #import <AddressBook/AddressBook.h> #import <AddressBookUI/AddressBookUI.h> @interface LocalAddressBookController : UIViewController<ABPersonViewControllerDelegate,ABPeoplePickerNavigationControllerDelegate,ABNewPersonViewControllerDelegate> { ABPeoplePickerNavigationController *picker; ABNewPersonViewController *personViewController; } @end 在LocalAddressBookController.m文件中 #import "LocalAddressBookController.h" #import "PublicHeader.h" @implementation LocalAddressBookController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; picker = [[ABPeoplePickerNavigationController alloc]init]; picker.view.frame = CGRectMake(0, 0, Screen_width, Screen_height-48); picker.peoplePickerDelegate = self; picker.delegate = self; //為了隱藏右上角的“取消”按鈕 [picker setHidesBottomBarWhenPushed:YES]; [picker setNavigationBarHidden:NO animated:NO];//顯示上方的NavigationBar和搜索框 [self.view addSubview:picker.view]; } #pragma mark UINavigationControllerDelegate methods //隱藏“取消”按鈕 - (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated { UIView *custom = [[UIView alloc] initWithFrame:CGRectMake(0.0f,0.0f,0.0f,0.0f)]; UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithCustomView:custom]; [viewController.navigationItem setRightBarButtonItem:btn animated:NO]; [btn release]; [custom release]; } #pragma mark - peoplePickerDelegate Methods -(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person { // [picker setNavigationBarHidden:NO animated:NO]; NSLog(@"%@", (NSString*)ABRecordCopyCompositeName(person)); return YES; } -(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier { return YES; } -(BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{ return YES; } //“取消”按鈕的委托響應方法 -(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker { //assigning control back to the main controller [picker dismissModalViewControllerAnimated:YES]; }
//……
@end
ios6 運行效果:
ios7 運行效果:
經驗:
當我們將系統通訊錄整個引入的時候,在通訊錄的右上角有一個系統自帶的“取消”按鈕。如何才能將這個取消按鈕隱藏呢?
(1)方法1:如果你的應用程序是用企業證書開發,不需要提交到appStore進行審核,那么答案非常簡單,為響應的piker增加如下代碼即可:
[picker setAllowsCancel:NO];
(2)方法二:上面的方法是非公開方法,是無法通過appStore審核的。如果想通過審核。可以嘗試使用如下方法:
前提:設置 picker.delegate = self; 然后實現如下委托方法 - (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated { UIView *custom = [[UIView alloc] initWithFrame:CGRectMake(0.0f,0.0f,0.0f,0.0f)]; UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithCustomView:custom]; //UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addAction)]; [viewController.navigationItem setRightBarButtonItem:btn animated:NO]; [btn release]; [custom release]; }
或者:(比上面更好)
前提:設置 picker.delegate = self; 然后實現如下委托方法,下面實現的效果,要比上面的好。上面實現的效果,當點擊“搜索”框時,“取消”按鈕還會重新出現。 - (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated { // Here we want to remove the 'Cancel' button, but only if we're showing // either of the ABPeoplePickerNavigationController's top two controllers if ([navigationController.viewControllers indexOfObject:viewController] <= 1) { viewController.navigationItem.rightBarButtonItem = nil; } }
2、逐條讀取通訊錄中的每一條聯系人信息。
方法:在上述類中,直接添加如下方法即可
在LocalAddressBookController.h文件中 #import <UIKit/UIKit.h> #import <AddressBook/AddressBook.h> #import <AddressBookUI/AddressBookUI.h> @interface LocalAddressBookController : { UITextView *textView; } @end 在LocalAddressBookController.m文件中 #import "LocalAddressBookController.h" #import "PublicHeader.h" @implementation LocalAddressBookController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, Screen_width, Screen_height)]; [self getAddressBook]; [self.view addSubview:textView]; } //獲取通訊錄中的所有屬性,並存儲在 textView 中,已檢驗,切實可行。兼容io6 和 ios 7 ,而且ios7還沒有權限確認提示。 -(void)getAddressBook { ABAddressBookRef addressBook = ABAddressBookCreate(); CFArrayRef results = ABAddressBookCopyArrayOfAllPeople(addressBook); for(int i = 0; i < CFArrayGetCount(results); i++) { ABRecordRef person = CFArrayGetValueAtIndex(results, i); //讀取firstname NSString *personName = (NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty); if(personName != nil) textView.text = [textView.text stringByAppendingFormat:@"\n姓名:%@\n",personName]; //讀取lastname NSString *lastname = (NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty); if(lastname != nil) textView.text = [textView.text stringByAppendingFormat:@"%@\n",lastname]; //讀取middlename NSString *middlename = (NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty); if(middlename != nil) textView.text = [textView.text stringByAppendingFormat:@"%@\n",middlename]; //讀取prefix前綴 NSString *prefix = (NSString*)ABRecordCopyValue(person, kABPersonPrefixProperty); if(prefix != nil) textView.text = [textView.text stringByAppendingFormat:@"%@\n",prefix]; //讀取suffix后綴 NSString *suffix = (NSString*)ABRecordCopyValue(person, kABPersonSuffixProperty); if(suffix != nil) textView.text = [textView.text stringByAppendingFormat:@"%@\n",suffix]; //讀取nickname呢稱 NSString *nickname = (NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty); if(nickname != nil) textView.text = [textView.text stringByAppendingFormat:@"%@\n",nickname]; //讀取firstname拼音音標 NSString *firstnamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty); if(firstnamePhonetic != nil) textView.text = [textView.text stringByAppendingFormat:@"%@\n",firstnamePhonetic]; //讀取lastname拼音音標 NSString *lastnamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty); if(lastnamePhonetic != nil) textView.text = [textView.text stringByAppendingFormat:@"%@\n",lastnamePhonetic]; //讀取middlename拼音音標 NSString *middlenamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonMiddleNamePhoneticProperty); if(middlenamePhonetic != nil) textView.text = [textView.text stringByAppendingFormat:@"%@\n",middlenamePhonetic]; //讀取organization公司 NSString *organization = (NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty); if(organization != nil) textView.text = [textView.text stringByAppendingFormat:@"%@\n",organization]; //讀取jobtitle工作 NSString *jobtitle = (NSString*)ABRecordCopyValue(person, kABPersonJobTitleProperty); if(jobtitle != nil) textView.text = [textView.text stringByAppendingFormat:@"%@\n",jobtitle]; //讀取department部門 NSString *department = (NSString*)ABRecordCopyValue(person, kABPersonDepartmentProperty); if(department != nil) textView.text = [textView.text stringByAppendingFormat:@"%@\n",department]; //讀取birthday生日 NSDate *birthday = (NSDate*)ABRecordCopyValue(person, kABPersonBirthdayProperty); if(birthday != nil) textView.text = [textView.text stringByAppendingFormat:@"%@\n",birthday]; //讀取note備忘錄 NSString *note = (NSString*)ABRecordCopyValue(person, kABPersonNoteProperty); if(note != nil) textView.text = [textView.text stringByAppendingFormat:@"%@\n",note]; //第一次添加該條記錄的時間 NSString *firstknow = (NSString*)ABRecordCopyValue(person, kABPersonCreationDateProperty); NSLog(@"第一次添加該條記錄的時間%@\n",firstknow); //最后一次修改該條記錄的時間 NSString *lastknow = (NSString*)ABRecordCopyValue(person, kABPersonModificationDateProperty); NSLog(@"最后一次修改該條記錄的時間%@\n",lastknow); //獲取email多值 ABMultiValueRef email = ABRecordCopyValue(person, kABPersonEmailProperty); int emailcount = ABMultiValueGetCount(email); for (int x = 0; x < emailcount; x++) { //獲取email Label NSString* emailLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(email, x)); //獲取email值 NSString* emailContent = (NSString*)ABMultiValueCopyValueAtIndex(email, x); textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",emailLabel,emailContent]; } //讀取地址多值 ABMultiValueRef address = ABRecordCopyValue(person, kABPersonAddressProperty); int count = ABMultiValueGetCount(address); for(int j = 0; j < count; j++) { //獲取地址Label NSString* addressLabel = (NSString*)ABMultiValueCopyLabelAtIndex(address, j); textView.text = [textView.text stringByAppendingFormat:@"%@\n",addressLabel]; //獲取該label下的地址6屬性 NSDictionary* personaddress =(NSDictionary*) ABMultiValueCopyValueAtIndex(address, j); NSString* country = [personaddress valueForKey:(NSString *)kABPersonAddressCountryKey]; if(country != nil) textView.text = [textView.text stringByAppendingFormat:@"國家:%@\n",country]; NSString* city = [personaddress valueForKey:(NSString *)kABPersonAddressCityKey]; if(city != nil) textView.text = [textView.text stringByAppendingFormat:@"城市:%@\n",city]; NSString* state = [personaddress valueForKey:(NSString *)kABPersonAddressStateKey]; if(state != nil) textView.text = [textView.text stringByAppendingFormat:@"省:%@\n",state]; NSString* street = [personaddress valueForKey:(NSString *)kABPersonAddressStreetKey]; if(street != nil) textView.text = [textView.text stringByAppendingFormat:@"街道:%@\n",street]; NSString* zip = [personaddress valueForKey:(NSString *)kABPersonAddressZIPKey]; if(zip != nil) textView.text = [textView.text stringByAppendingFormat:@"郵編:%@\n",zip]; NSString* coutntrycode = [personaddress valueForKey:(NSString *)kABPersonAddressCountryCodeKey]; if(coutntrycode != nil) textView.text = [textView.text stringByAppendingFormat:@"國家編號:%@\n",coutntrycode]; } //獲取dates多值 ABMultiValueRef dates = ABRecordCopyValue(person, kABPersonDateProperty); int datescount = ABMultiValueGetCount(dates); for (int y = 0; y < datescount; y++) { //獲取dates Label NSString* datesLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(dates, y)); //獲取dates值 NSString* datesContent = (NSString*)ABMultiValueCopyValueAtIndex(dates, y); textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",datesLabel,datesContent]; } //獲取kind值 CFNumberRef recordType = ABRecordCopyValue(person, kABPersonKindProperty); if (recordType == kABPersonKindOrganization) { // it's a company NSLog(@"it's a company\n"); } else { // it's a person, resource, or room NSLog(@"it's a person, resource, or room\n"); } //獲取IM多值 ABMultiValueRef instantMessage = ABRecordCopyValue(person, kABPersonInstantMessageProperty); for (int l = 1; l < ABMultiValueGetCount(instantMessage); l++) { //獲取IM Label NSString* instantMessageLabel = (NSString*)ABMultiValueCopyLabelAtIndex(instantMessage, l); textView.text = [textView.text stringByAppendingFormat:@"%@\n",instantMessageLabel]; //獲取該label下的2屬性 NSDictionary* instantMessageContent =(NSDictionary*) ABMultiValueCopyValueAtIndex(instantMessage, l); NSString* username = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageUsernameKey]; if(username != nil) textView.text = [textView.text stringByAppendingFormat:@"username:%@\n",username]; NSString* service = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageServiceKey]; if(service != nil) textView.text = [textView.text stringByAppendingFormat:@"service:%@\n",service]; } //讀取電話多值 ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty); for (int k = 0; k<ABMultiValueGetCount(phone); k++) { //獲取電話Label NSString * personPhoneLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k)); //獲取該Label下的電話值 NSString * personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, k); textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",personPhoneLabel,personPhone]; } //獲取URL多值 ABMultiValueRef url = ABRecordCopyValue(person, kABPersonURLProperty); for (int m = 0; m < ABMultiValueGetCount(url); m++) { //獲取電話Label NSString * urlLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(url, m)); //獲取該Label下的電話值 NSString * urlContent = (NSString*)ABMultiValueCopyValueAtIndex(url,m); textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",urlLabel,urlContent]; } //讀取照片 NSData *image = (NSData*)ABPersonCopyImageData(person); UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(200, 0, 50, 50)]; [myImage setImage:[UIImage imageWithData:image]]; myImage.opaque = YES; [textView addSubview:myImage]; } CFRelease(results); CFRelease(addressBook); }
//……
@end
ios7運行效果:
參考:
想擴展右上角“取消”按鈕的可以看 http://d2100.com/questions/6864
隱藏右上角“取消”按鈕的方法 (有可行代碼) http://stackoverflow.com/questions/1611499/abpeoplepickernavigationcontroller-remove-cancel-button-without-using-privat
如何使用ios addressBook 總結的很全面,有概括性 http://www.cnblogs.com/y041039/archive/2012/03/22/2411771.html