这篇文章给大家分享的是有关iOS如何实现从通讯录中选择联系人的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
有时候APP需要用户输入一位联系人的姓名和电话,除了用户手动输入,一般也允许用户从通讯录中选择一位联系人(图1),下面的代码就是使用系统的<AddressBookUI/AddressBookUI.h>库实现这一需求。
图1
完整代码:
#import "ViewController.h" #import <AddressBookUI/AddressBookUI.h> @interface ViewController ()<ABPeoplePickerNavigationControllerDelegate> @property (weak, nonatomic) IBOutlet UITextField *nameTextField; @property (weak, nonatomic) IBOutlet UITextField *phoneTextField; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } //用户点击选择按钮 - (IBAction)clickSelect:(UIButton *)sender { ABPeoplePickerNavigationController *picker =[[ABPeoplePickerNavigationController alloc] init]; picker.peoplePickerDelegate = self; [self presentViewController:picker animated:YES completion:nil]; } //这个方法在用户取消选择时调用 - (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker { [self dismissViewControllerAnimated:YES completion:^{}]; } //这个方法在用户选择一个联系人后调用 -(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person{ [self displayPerson:person]; [self dismissViewControllerAnimated:YES completion:^{}]; } //获得选中person的信息 - (void)displayPerson:(ABRecordRef)person { NSString *firstName = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty); NSString *middleName = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty); NSString *lastname = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty); NSMutableString *nameStr = [NSMutableString string]; if (lastname!=nil) { [nameStr appendString:lastname]; } if (middleName!=nil) { [nameStr appendString:middleName]; } if (firstName!=nil) { [nameStr appendString:firstName]; } NSString* phone = nil; ABMultiValueRef phoneNumbers = ABRecordCopyValue(person,kABPersonPhoneProperty); if (ABMultiValueGetCount(phoneNumbers) > 0) { phone = (__bridge_transfer NSString*)ABMultiValueCopyValueAtIndex(phoneNumbers, 0); } else { phone = @"[None]"; } //可以把-、+86、空格这些过滤掉 NSString *phoneStr = [phone stringByReplacingOccurrencesOfString:@"-" withString:@""]; phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"+86" withString:@""]; phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@" " withString:@""]; [self.nameTextField setText:nameStr]; [self.phoneTextField setText:phoneStr]; } @end
感谢各位的阅读!关于“iOS如何实现从通讯录中选择联系人”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。