我想在 iPhone 中获取联系人详细信息,包括名字、姓氏、电话号码、电话号码类型、电子邮件地址、电子邮件地址类型等信息。
任何人都可以帮助我吗?
我想用特定 iPhone 中的联系方式制作一个 .csv 文件。我想获取 iPhone 通讯录数据。
我想在 iPhone 中获取联系人详细信息,包括名字、姓氏、电话号码、电话号码类型、电子邮件地址、电子邮件地址类型等信息。
任何人都可以帮助我吗?
我想用特定 iPhone 中的联系方式制作一个 .csv 文件。我想获取 iPhone 通讯录数据。
以下是获取 iPhone 通讯录所有信息的代码...
-(void)collectContacts
{
NSMutableDictionary *myAddressBook = [[NSMutableDictionary alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
for(int i = 0;i<ABAddressBookGetPersonCount(addressBook);i++)
{
ABRecordRef ref = CFArrayGetValueAtIndex(people, i);
// Get First name, Last name, Prefix, Suffix, Job title
NSString *firstName = (NSString *)ABRecordCopyValue(ref,kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(ref,kABPersonLastNameProperty);
NSString *prefix = (NSString *)ABRecordCopyValue(ref,kABPersonPrefixProperty);
NSString *suffix = (NSString *)ABRecordCopyValue(ref,kABPersonSuffixProperty);
NSString *jobTitle = (NSString *)ABRecordCopyValue(ref,kABPersonJobTitleProperty);
[myAddressBook setObject:firstName forKey:@"firstName"];
[myAddressBook setObject:lastName forKey:@"lastName"];
[myAddressBook setObject:prefix forKey:@"prefix"];
[myAddressBook setObject:suffix forKey:@"suffix"];
[myAddressBook setObject:jobTitle forKey:@"jobTitle"];
NSMutableArray *arPhone = [[NSMutableArray alloc] init];
ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phones, j);
NSString *phoneLabel =(NSString*) ABAddressBookCopyLocalizedLabel (ABMultiValueCopyLabelAtIndex(phones, j));
NSString *phoneNumber = (NSString *)phoneNumberRef;
NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];
[temp setObject:phoneNumber forKey:@"phoneNumber"];
[temp setObject:phoneLabel forKey:@"phoneNumber"];
[arPhone addObject:temp];
[temp release];
}
[myAddressBook setObject:arPhone forKey:@"Phone"];
[arPhone release];
CFStringRef address;
CFStringRef label;
ABMutableMultiValueRef multi = ABRecordCopyValue(ref, kABPersonAddressProperty);
for (CFIndex i = 0; i < ABMultiValueGetCount(multi); i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
CFStringRef readableLabel = ABAddressBookCopyLocalizedLabel(label);
address = ABMultiValueCopyValueAtIndex(multi, i);
CFRelease(address);
CFRelease(label);
}
ABMultiValueRef emails = ABRecordCopyValue(ref, kABPersonEmailProperty);
NSMutableArray *arEmail = [[NSMutableArray alloc] init];
for(CFIndex idx = 0; idx < ABMultiValueGetCount(emails); idx++)
{
CFStringRef emailRef = ABMultiValueCopyValueAtIndex(emails, idx);
NSString *strLbl = (NSString*) ABAddressBookCopyLocalizedLabel (ABMultiValueCopyLabelAtIndex (emails, idx));
NSString *strEmail_old = (NSString*)emailRef;
NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];
[temp setObject:strEmail_old forKey:@"strEmail_old"];
[temp setObject:strLbl forKey:@"strLbl"];
[arEmail addObject:temp];
[temp release];
}
[myAddressBook setObject:arEmail forKey:@"Email"];
[arEmail release];
}
[self createCSV:myAddressBook];
}
-(void) createCSV :(NSMutableDictionary*)arAddressData
{
NSMutableString *stringToWrite = [[NSMutableString alloc] init];
[stringToWrite appendString:[NSString stringWithFormat:@"%@,",[arAddressData valueForKey:@"firstName"]]];
[stringToWrite appendString:[NSString stringWithFormat:@"%@,",[arAddressData valueForKey:@"lastName"]]];
[stringToWrite appendString:[NSString stringWithFormat:@"%@,",[arAddressData valueForKey:@"jobTitle"]]];
//[stringToWrite appendString:@"fname, lname, title, company, phonetype1, value1,phonetype2,value,phonetype3,value3phonetype4,value4,phonetype5,value5,phonetype6,value6,phonetype7,value7,phonetype8,value8,phonetype9,value9,phonetype10,value10,email1type,email1value,email2type,email2value,email3type,email3value,email4type,email4value,email5type,email5value,website1,website2,website3"];
NSMutableArray *arPhone = (NSMutableArray*) [arAddressData valueForKey:@"Phone"];
for(int i = 0 ;i<[arPhone count];i++)
{
NSMutableDictionary *temp = (NSMutableDictionary*) [arPhone objectAtIndex:i];
[stringToWrite appendString:[NSString stringWithFormat:@"%@,",[temp valueForKey:@"phoneNumber"]]];
[stringToWrite appendString:[NSString stringWithFormat:@"%@,",[temp valueForKey:@"phoneNumber"]]];
[temp release];
}
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString *strBackupFileLocation = [NSString stringWithFormat:@"%@/%@", documentDirectory,@"ContactList.csv"];
[stringToWrite writeToFile:strBackupFileLocation atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
我使用上面的 iApple 代码作为起点,并从中创建了一个工作版本——这个版本只是将所有地址簿条目收集在一个数组中。如上所述,最初的 iApple 无法正常工作,其中存在一些错误。这个工作,并经过测试。
注意:这不会返回任何没有设置名称的联系人 - 您可以为自己的代码删除它,我这样做是因为我只需要设置名称的联系人,并且 NSMutableDictionary 不喜欢 nil 条目(崩溃)。
在我自己的地址簿中,我有一些条目只是一封电子邮件——我不确定它们是如何到达那里的,但肯定有可能有没有名字的地址簿条目。在遍历地址簿时请记住这一点。
我根据 Apple 的建议使用全名 - ABRecordCopyCompositeName 按用户指定的顺序返回名字和姓氏的组合。
最后,我把它变成了一个静态方法,并把它放在一个辅助类中。
这是与 ARC 一起使用的!
// returns an array of dictionaries
// each dictionary has values: fullName, phoneNumbers, emails
// fullName is a string
// phoneNumbers is an array of strings
// emails is an array of strings
+ (NSArray *)collectAddressBookContacts {
NSMutableArray *allContacts = [[NSMutableArray alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
for(int i = 0;i<ABAddressBookGetPersonCount(addressBook);i++)
{
NSMutableDictionary *aPersonDict = [[NSMutableDictionary alloc] init];
ABRecordRef ref = CFArrayGetValueAtIndex(people, i);
NSString *fullName = (__bridge NSString *) ABRecordCopyCompositeName(ref);
if (fullName) {
[aPersonDict setObject:fullName forKey:@"fullName"];
// collect phone numbers
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++) {
NSString *phoneNumber = (__bridge NSString *) ABMultiValueCopyValueAtIndex(phones, j);
[phoneNumbers addObject:phoneNumber];
}
[aPersonDict setObject:phoneNumbers forKey:@"phoneNumbers"];
// collect emails - key "emails" will contain an array of email addresses
ABMultiValueRef emails = ABRecordCopyValue(ref, kABPersonEmailProperty);
NSMutableArray *emailAddresses = [[NSMutableArray alloc] init];
for(CFIndex idx = 0; idx < ABMultiValueGetCount(emails); idx++) {
NSString *email = (__bridge NSString *)ABMultiValueCopyValueAtIndex(emails, idx);
[emailAddresses addObject:email];
}
[aPersonDict setObject:emailAddresses forKey:@"emails"];
// if you want to collect any other info that's stored in the address book, it follows the same pattern.
// you just need the right kABPerson.... property.
[allContacts addObject:aPersonDict];
} else {
// Note: I have a few entries in my phone that don't have a name set
// Example one could have just an email address in their address book.
}
}
return allContacts;
}
首先,您需要使用地址簿框架,因此必须将其添加到您的 Xcode 项目中。
接下来,您需要将任务分解为几个步骤。
1) 获取通讯录中的人
2) 创建您的 .csv 文件。我假设您了解使用字符来分隔字段的 CSV 文件格式以及何时添加返回字符以便您拥有格式正确的文件。如果您需要帮助,这可能留给另一个问题线程。
3) 将您的 .csv 文件保存在某处
1) 要获取地址簿中所有人的数组,您可以执行以下操作。ABAddressBook 的参考文档在此处。它应该对帮助您访问数据非常有帮助。
ABAddressBook *sharedBook = [ABAddressBook sharedAddressBook];
NSArray *peopleList = [sharedBook people];
2)您将不得不遍历每个人并构建您的整体 csv 数据。通常您会在 NSString 中手动创建 csv 数据,然后将其转换为 NSData 并将 NSData 保存到文件中。如果您正在处理大量数据,这并不理想。如果是这种情况,那么您可能需要一些代码将您的 csv 数据分块写入文件,以便您可以随时释放内存。为简单起见,我的代码仅显示您创建完整文件然后保存整个作品。
NSString *csvString = @"";
for(ABPerson *aPerson in peopleList) {
//Do something here to write each property you want to the CSV file.
csvString = [csvString stringByAppendingFormat:@"'%@',"
[aPerson valueForProperty:kABFirstNameProperty]];
}
NSData *csvData = [csvString dataUsingEncoding:NSUTF8StringEncoding];
3)把你的文件写到某个地方
//This is an example of writing your csv data to a file that will be saved in the application's sand box directory.
//This file could be extracted using iTunes file sharing.
//Get the proper path to save the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"my_file.csv"];
//Actually write the data
BOOL isSuccessful = [csvData writeToFile:fullPath atomically:NO];
if(isSuccessful) {
//Do something if the file was written
} else {
//Do something if there was an error writing the file
}
请参阅地址簿 API特别是导入和导出人员和组记录
还检查此博客中的通讯簿测试示例