iOS中获取通讯录信息

在获取通讯录联系人相关信息时,要特别注意的是必须在获取前指定要获取的具体字段,另外,在添加到数组或字典中的联系人信息要注意提供默认值,防止数据为nil时崩溃。

指定要获取的数据:

1
2
3
4
5
6
7
8
9
//姓:CNContactFamilyNameKey
//名:CNContactGivenNameKey
//手机号:CNContactPhoneNumbersKey
//邮箱:CNContactEmailAddressesKey
//备注:CNContactNoteKey
//公司名称:CNContactOrganizationNameKey
NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey,CNContactEmailAddressesKey,CNContactNoteKey,CNContactOrganizationNameKey];

CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];

开始获取数据:

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
NSMutableArray *contactBook = [NSMutableArray alloc] initWithCapacity:0]; 
CNContactStore *contactStore = [[CNContactStore alloc] init];

[contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {

//姓名
NSString *lastName = contact.givenName ? contact.givenName : @"";
NSString *familyName = contact.familyName ? contact.familyName : @"";
//手机号码
NSString *mobile = @"";
NSArray *phoneNumbers = contact.phoneNumbers;
if (phoneNumbers.count) {
CNLabeledValue *labelValue = phoneNumbers[0];
CNPhoneNumber *phoneNumber = labelValue.value;

NSString * string = phoneNumber.stringValue ;
//去掉电话中的特殊字符
string = [string stringByReplacingOccurrencesOfString:@"+86" withString:@""];
string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
string = [string stringByReplacingOccurrencesOfString:@"(" withString:@""];
string = [string stringByReplacingOccurrencesOfString:@")" withString:@""];
string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
mobile = string;
}

//邮箱
NSString *email = @"";

NSArray *emails = contact.emailAddresses;
if (emails.count) {
CNLabeledValue *emailValue = emails[0];
NSString *emailAddress = [NSString stringWithFormat:@"%@",emailValue.value];
email = emailAddress;
}


//备注
NSString *note = contact.note ? contact.note : @"";
//公司
NSString *organization = contact.organizationName ? contact.organizationName : @"";

NSDictionary *dic = @{@"email":email,
@"familyName":familyName,
@"lastName":lastName,
@"mobile":mobile,
@"notes":note,
@"organization":organization
};
[contactBook addObject:dic];

}];

contactBook就是获取到的通讯录数据。