如何在 CNContact 中 update/merge 联系人

How to update/merge contacts in CNContact

我正在尝试在我的 contacts.When 中导入 vcf 文件,第一次保存联系人时它导入成功,没有 problem.But 当我尝试更新它正在做的同一个联系人时 nothing.What 我想?我想如果我会更新联系人然后 phone 添加的号码存在 contact.I 我正在使用 CNContact。

保存联系人:

-(void)saveVCardContacts:(CNContact *)contact{
    NSError * error;


    CNSaveRequest *saveRequest = [[CNSaveRequest alloc]init];
    [saveRequest addContact:[contact mutableCopy] toContainerWithIdentifier:nil];
    BOOL success =  [self.store executeSaveRequest:saveRequest error:&error];

    if(success)
        NSLog(@"import successfully");
    else
        NSLog(@"Error = %@",error);

}

更新

-(void)updateVCardContacts:(CNContact *)contact{


    NSError *error; 
    CNSaveRequest *saveRequest = [[CNSaveRequest alloc]init];
    [saveRequest updateContact:[contact mutableCopy]];
    BOOL success =  [self.store executeSaveRequest:saveRequest error:&error];

    if(success)
         NSLog(@"update successfully");
    else
        NSLog(@"Error = %@",error);


}

您可以只用名字替换您的电话号码

CNSaveRequest * saveRequest = [[CNSaveRequest alloc]init];
    CNContactStore * store = [[CNContactStore alloc]init];

    NSArray*  arrFetchedcontact = nil;
    @try {

        NSError * err = nil;
        NSArray * keytoFetch = @[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey];
        NSPredicate * predicate = [CNContact predicateForContactsMatchingName:GivenNames];
        arrFetchedcontact = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keytoFetch error:&err];
    }
    @catch (NSException *exception) {
        NSLog(@"description = %@",[exception description]);
    }

    if([arrFetchedcontact count] > 0)
    {

        NSLog(@"ArrFetchedContact %@",arrFetchedcontact);


        CNMutableContact * contactToUpdate = [[arrFetchedcontact objectAtIndex:0] mutableCopy];
        NSMutableArray * arrNumbers = [[contactToUpdate phoneNumbers] mutableCopy];
        [arrNumbers removeObjectAtIndex:0];

        CNLabeledValue * homePhone = [CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberMobile value:[CNPhoneNumber phoneNumberWithStringValue:FieldNumbers]];

        NSLog(@"Print Homephone %@",homePhone);


        [arrNumbers addObject:homePhone];
        [contactToUpdate setPhoneNumbers:arrNumbers];

        [saveRequest updateContact:contactToUpdate];

        @try {

            NSLog(@"Success %d",[store executeSaveRequest:saveRequest error:nil]);


        }
        @catch (NSException *exception) {
            NSLog(@"description = %@",[exception description]);
        }
    }

字段编号是您要用给定名称替换的数字

名字是那个号码的人的名字