initWithVCardRepresentation
仍然是將您的電子名片變成ABPerson
的最明智的方式。
只需使用它的結果在您的地址簿中找到匹配的人員,然後遍歷vCard屬性,將它們放入現有記錄中。最後的保存會加強你的改變。
以下示例假定唯一的「密鑰」爲last-name
,first-name
。如果您想要包含沒有列出名稱的公司或者其他任何公司,您可以修改搜索元素,或者您可以通過獲取[AddressBook people]來更改迭代方案,然後迭代人員並僅使用鍵值對符合您的滿意度。
- (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];
}