将vCard数据直接添加到系统通讯簿中 [英] Adding vCard data directly to the system Address Book

查看:232
本文介绍了将vCard数据直接添加到系统通讯簿中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am designing a QR code reader, and it needs to detect and import contact cards in vCard format (.vcf).

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

is there a way to add the card data to the system Address Book directly, or do I need to parse the vCard myself and add each field individually?

推荐答案

如果你在iOS 5或更高版本上运行,这段代码可以解决这个问题:

If you're running on iOS 5 or later, this code should do the trick:

#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框架。

Make sure to link to the AddressBook framework in your project.

这篇关于将vCard数据直接添加到系统通讯簿中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆