Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用iOS中的CNContacts检查联系人列表中是否存在联系人号码_Ios_Cncontact - Fatal编程技术网

使用iOS中的CNContacts检查联系人列表中是否存在联系人号码

使用iOS中的CNContacts检查联系人列表中是否存在联系人号码,ios,cncontact,Ios,Cncontact,我正在实现一个逻辑来检查联系人列表中是否存在联系人,并根据这个结果插入联系人。我目前的进展: __block NSString *strPhoneNumber = @"1093874652"; if ([CNContactStore class]) { CNContactStore *addressBook = [[CNContactStore alloc] init]; NSArray *keysToFetch =@[CNContactPhoneNumbersKey];

我正在实现一个逻辑来检查联系人列表中是否存在联系人,并根据这个结果插入联系人。我目前的进展:

__block NSString *strPhoneNumber = @"1093874652";

if ([CNContactStore class]) {
    CNContactStore *addressBook = [[CNContactStore alloc] init];

    NSArray *keysToFetch =@[CNContactPhoneNumbersKey];
                 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{


    NSError *error = nil;
    CNContactFetchRequest *fetchRequest =[[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];

    __block BOOL isExists = NO;

    [addressBook enumerateContactsWithFetchRequest:fetchRequest error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {

    NSArray *phoneNumbers =[[contact.phoneNumbers valueForKey:@"value"] valueForKey:@"digits"];


    if ([phoneNumbers containsObject:strPhoneNumber]) {
        isExists = YES;
        *stop = YES;
    }
    else
        isExists = NO;

    }];

    dispatch_async(dispatch_get_main_queue(), ^{

    if (isExists == NO) {
     //This is the method for saving the contacts. I'm not implementing here.                    
     [self saveContactWithName:@"John Doe" withContactEmail:@"johndoe@abc.com@" withContactPhone:str];                                 
    }

    });
  });
}

现在,问题是在枚举之后,if(isExists==NO)下的代码会触发多次并多次保存联系人。如何停止它?我唯一需要的是,如果联系人退出,那么不要保存它,否则只保存一次。任何帮助都将不胜感激

替换代码中的以下部分

NSArray *phoneNumbers = [[contact.phoneNumbers valueForKey:@"value"] valueForKey:@"digits"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self == [c] %@", strPhoneNumber];
NSArray *filtered = [phoneNumbers filteredArrayUsingPredicate:predicate];
if ([filtered count] > 0) {
    isExists = YES;
    *stop = YES;
}
else
    isExists = NO;

}];

为什么第二个
调度\u async()
?为什么不直接存储它而不是设置
isExists
?如果([phoneNumbers containsObject:strPhoneNumber])将始终为false,因为
strPhoneNumber
元素中不存在
phoneNumbers
实例。您需要检查字符串是否与谓词相等或其他内容。@Droppy:您是对的,不需要第二个
调度\u async()
。我打算放弃它。@Akhilrajtr:strPhoneNumber在顶部提到。好的,我会试试。我认为像[c]这样的
可以替换为
==[c]
,更新答案