AddressBook框架通过使用ABPerson方法为使用vCard初始化ABPerson提供了一种很好的方法。
我想要做的是用某个vCard更新一个联系人。我不能使用initWithVCardRepresentation:,因为这将给我一个新的ABPerson对象和一个新的uniqueId,并且我希望在这些更改之间保持uniqueId。
做这样的事情有什么简单的方法?
谢谢!
发布于 2012-07-16 18:28:14
initWithVCardRepresentation仍然是将vCard转换为ABPerson的最巧妙的方式。
只需使用它的结果在通讯簿中找到匹配的人,然后遍历vCard属性,将它们放到现有的记录中。最后的保存会使你的改变变硬。
下面的示例假设唯一的“键”将是last-name,first-name。如果您想包括没有名字上市的公司或其他什么,您可以修改搜索元素,或者您可以通过获取AddressBook人员来更改迭代方案,然后对人员进行迭代,并且只使用键-值对匹配到您满意的那些记录。
- (void)initOrUpdateVCardData:(NSData*)newVCardData {
ABPerson* newVCard = [[ABPerson alloc] initWithVCardRepresentation:newVCardData];
ABSearchEleemnt* lastNameSearchElement
= [ABPerson searchElementForProperty:kABLastNameProperty
label:nil
key:nil
value:[newVCard valueForProperty:kABLastNameProperty]
comparison:kABEqualCaseInsensitive];
ABSearchEleemnt* firstNameSearchElement
= [ABPerson searchElementForProperty:kABFirstNameProperty
label:nil
key:nil
value:[newVCard valueForProperty:kABFirstNameProperty]
comparison:kABEqualCaseInsensitive];
NSArray* searchElements
= [NSArray arrayWithObjects:lastNameSearchElement, firstNameSearchElement, nil];
ABSearchElement* searchCriteria
= [ABSearchElement searchElementForConjunction:kABSearchAnd children:searchElements];
AddressBook* myAddressBook = [AddressBook sharedAddressBook];
NSArray* matchingPersons = [myAddressBook recordsMatchingSearchElement:searchCriteria];
if (matchingPersons.count == 0)
{
[myAddressBook addRecord:newVCard];
}
else if (matchingPersons.count > 1)
{
// decide how to handle error yourself here: return, or resolve conflict, or whatever
}
else
{
ABRecord* existingPerson = matchingPersons.lastObject;
for (NSString* property in [ABPerson properties]) // i.e. *all* potential properties
{
// if the property doesn't exist in the address book, value will be nil
id value = [newVCard valueForProperty:property];
if (value)
{
NSError* error;
if (![existingPerson setValue:value forProperty:property error:&error] || error)
// handle error
}
}
// newVCard with it's new unique-id will now be thrown away
}
[myAddressBook save];
}https://stackoverflow.com/questions/11472611
复制相似问题