如何在CNContact

时间:2017-05-16 13:10:48

标签: ios objective-c iphone cncontact

我正在尝试在我的联系人中导入vcf文件。当我第一次保存联系人时,它导入成功,没问题。但是当我尝试更新同一个联系人时,它什么都不做。我想要什么?我想如果我将更新联系人然后电话号码添加现有联系人。我正在使用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);


}

1 个答案:

答案 0 :(得分:3)

您可以仅使用姓名

替换您的号码
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]);
        }
    }

字段编号是您要用给定名称

替换的编号

给定名称是具有该号码的人的名称