亲宝软件园·资讯

展开

iOS从通讯录中选择联系人 iOS实现从通讯录中选择联系人

imJackXu 人气:0
想了解iOS实现从通讯录中选择联系人的相关内容吗,imJackXu在本文为您仔细讲解iOS从通讯录中选择联系人的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:iOS通讯录选择联系人,iOS通讯录联系人,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

源代码下载:点击打开链接

加载全部内容

相关教程
猜你喜欢
用户评论