将vCard数据直接添加到系统通讯簿中

时间:2011-11-14 01:04:30

标签: objective-c ios addressbook

我正在设计一个二维码阅读器,它需要检测和导入vCard格式的联系卡(.vcf)。

有没有办法直接将卡数据添加到系统地址簿,还是我需要自己解析vCard并单独添加每个字段?

3 个答案:

答案 0 :(得分:13)

如果您在iOS 5或更高版本上运行,此代码应该可以解决问题:

#import <AddressBook/AddressBook.h>

// This gets the vCard data from a file in the app bundle called vCard.vcf
//NSURL *vCardURL = [[NSBundle bundleForClass:self.class] URLForResource:@"vCard" withExtension:@"vcf"];
//CFDataRef vCardData = (CFDataRef)[NSData dataWithContentsOfURL:vCardURL];

// This version simply uses a string. I'm assuming you'll get that from somewhere else.
NSString *vCardString = @"vCardDataHere";
// This line converts the string to a CFData object using a simple cast, which doesn't work under ARC
CFDataRef vCardData = (CFDataRef)[vCardString dataUsingEncoding:NSUTF8StringEncoding];
// If you're using ARC, use this line instead:
//CFDataRef vCardData = (__bridge CFDataRef)[vCardString dataUsingEncoding:NSUTF8StringEncoding];

ABAddressBookRef book = ABAddressBookCreate();
ABRecordRef defaultSource = ABAddressBookCopyDefaultSource(book);
CFArrayRef vCardPeople = ABPersonCreatePeopleInSourceWithVCardRepresentation(defaultSource, vCardData);
for (CFIndex index = 0; index < CFArrayGetCount(vCardPeople); index++) {
    ABRecordRef person = CFArrayGetValueAtIndex(vCardPeople, index);
    ABAddressBookAddRecord(book, person, NULL);
}

CFRelease(vCardPeople);
CFRelease(defaultSource);
ABAddressBookSave(book, NULL);
CFRelease(book);

确保链接到项目中的AddressBook框架。

答案 1 :(得分:4)

Carter Allen的回答对我有用,只不过它导致我的应用程序在最终声明中崩溃CFRelease(book);

事实证明应删除CFRelease(person);语句。这样做会阻止我的应用崩溃。请参阅此答案以获取解释https://stackoverflow.com/a/1337086/881103

另请查看此页面上的“创建规则”和“获取规则”部分https://developer.apple.com/library/mac/#documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html

答案 2 :(得分:1)

联系人非常宽容,并会尽力导入您的vCard,但似乎您的地址不正确。应该有7个参数,用分号分隔:PO框,套件#,街道地址,城市,州,ZIP,国家。大多数人都离开了邮政信箱(和套件#),这就是典型地址在开头有一个分号(或两个)的原因。如果您的地址格式错误,参数可能会在错误的位置结束。

vCard中的各个字段由<return>终止:@“\ r”

您不需要CHARSET=utf-8