objective-c – 将vCard数据直接添加到系统通讯簿

前端之家收集整理的这篇文章主要介绍了objective-c – 将vCard数据直接添加到系统通讯簿前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在设计一个QR码阅读器,需要检测和导入vCard格式的联系人卡(.vcf).

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

解决方法

如果您在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框架.

猜你在找的C&C++相关文章