2

I'm trying to copy contacts between my Local contact source and the iCloud contact source and I'm not seeing any results. This code executes without error and seems like it should work, but I don't see the newly created contacts afterward. Anyone see any issues with it?

ABAddressBookRef addressBook = ABAddressBookCreate();

ABRecordRef abSourceSource = ABAddressBookGetSourceWithRecordID(addressBook, kABSourceTypeLocal);
ABRecordRef abDestinationSource = ABAddressBookGetSourceWithRecordID(addressBook, kABSourceTypeCardDAV);

CFArrayRef sourceContacts = ABAddressBookCopyArrayOfAllPeopleInSource(addressBook, abSourceSource);
CFArrayRef destinationContacts = ABAddressBookCopyArrayOfAllPeopleInSource(addressBook, abDestinationSource);

ABPersonCreatePeopleInSourceWithVCardRepresentation(abDestinationSource, ABPersonCreateVCardRepresentationWithPeople(sourceContacts));
ABPersonCreatePeopleInSourceWithVCardRepresentation(abSourceSource, ABPersonCreateVCardRepresentationWithPeople(destinationContacts)));

ABAddressBookSave(addressBook, NULL);
4

2 回答 2

4

还有一个更根本的问题 - 您没有正确调用 ABAddressBookGetSourceWithRecordID。它采用的第二个参数是一个 int,它指定地址簿中特定源的记录 ID。您正在向它传递一个描述特定源类型的常量。

您传递的常数 kABSourceTypeCardDav 始终为 4。但是,用户通讯录中 iCloud 源的记录 ID 可能非常不同。

您需要做的是枚举所有来源并测试它们的类型,如下所示:

NSArray *allSources = (NSArray*)ABAddressBookCopyArrayOfAllSources(addressBook);

for (int i = 0; i < allSources.count; i++) {
    ABRecordRef src = [allSources objectAtIndex:i];
    NSNumber *stObj = (NSNumber*)ABRecordCopyValue(src, kABSourceTypeProperty);
    ABSourceType st = (ABSourceType)[stObj intValue];

    if (st == kABSourceTypeCardDAV) {
        int recordID = ABRecordGetRecordID(src);
        break;
    }
}

然后你可以使用 recordID 作为第一个函数的参数

于 2012-04-05T22:44:36.893 回答
2

我想你忘了用 ABAddressBookAddRecord 添加记录。这是我的工作示例:

ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordRef abSource = ABAddressBookGetSourceWithRecordID(addressBook, kABSourceTypeLocal);
NSURL *theURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"some.vcf"];
NSData *vCardData = [NSData dataWithContentsOfURL:theURL];
NSLog(@"data %@", vCardData);
NSArray *createdPeople = (__bridge_transfer NSArray*)ABPersonCreatePeopleInSourceWithVCardRepresentation(abSource, (__bridge CFDataRef)vCardData);
NSLog(@"createdPeople %@", createdPeople);
CFErrorRef error = NULL;
bool ok;
for (id person in createdPeople) {
    error = NULL;
    ok = ABAddressBookAddRecord(addressBook, (__bridge ABRecordRef)person, &error);
    if (!ok) {
        NSLog(@"add err %@", error);  
        break;
    } 
}
if (ok) {
    error = NULL;
    BOOL isSaved = ABAddressBookSave(addressBook, &error);
    if (isSaved) {
        NSLog(@"saved..");
    }
    if (error != NULL) {
        NSLog(@"ABAddressBookSave %@", error);
    } 
}
CFRelease(addressBook);    
于 2011-11-11T13:16:55.227 回答