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

时间:2021-07-20 14:49:45

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

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

图1

完整代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#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

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

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

原文链接:https://blog.csdn.net/dolacmeng/article/details/50574258