欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-04 23:29:28
有时候app需要用户输入一位联系人的姓名和电话,除了用户手动输入,一般也允许用户从通讯录中选择一位联系人(图1),下面的代码就是使用系统的

有时候app需要用户输入一位联系人的姓名和电话,除了用户手动输入,一般也允许用户从通讯录中选择一位联系人(图1),下面的代码就是使用系统的<addressbookui/addressbookui.h>库实现这一需求。

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

图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

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

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