Copying contacts from one source to another

旧街凉风 提交于 2019-12-03 08:59:30

There is a more fundamental problem - you are not calling ABAddressBookGetSourceWithRecordID properly. The 2nd parameter it takes is an int that specifies the record id of a particular source in your address book. You are passing it a constant that describes the type of a particular source.

The constant you are passing, kABSourceTypeCardDav is always 4. However, the record id of the iCloud source in a user's address book can be something very different.

What you need to do is enumerate all the sources and test their types, like so:

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;
    }
}

Then you could use recordID as the argument to the first function

I think you forgot to add the records with ABAddressBookAddRecord. Here is my working example:

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);    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!