当前位置 : 主页 > 手机开发 > ios >

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

来源:互联网 收集:自由互联 发布时间:2022-05-11
有时候APP需要用户输入一位联系人的姓名和电话,除了用户手动输入,一般也允许用户从通讯录中选择一位联系人(图1),下面的代码就是使用系统的 AddressBookUI/AddressBookUI.h库 实现这

有时候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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。

【本文来自:美国大带宽服务器 http://www.558idc.com/mg.html提供,感恩】
上一篇:iOS实现联系人列表功能
下一篇:没有了
网友评论