我正在尝试在我的本地联系人源和iCloud联系人源之间复制联系人,但我没有看到任何结果。这段代码没有错误地执行,看起来应该可以工作,但之后我没有看到新创建的联系人。有人看到任何问题吗?
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);
答案 0 :(得分: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作为第一个函数的参数
答案 1 :(得分: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);