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

标签 ios cncontact

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

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

}];

关于ios - 在 iOS 中使用 CNContacts 检查联系人列表中是否存在联系人号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38454663/

相关文章:

ios - 在 AppStore 上,如何按地区不同更新我的应用程序?

iOS:在 for 循环中更新 NSMutableArray 的对象

ios - 带有 AutoLayout 的 UICollectionViewCell 在 iOS 10 中不起作用

ios - 访问 plist 数组 Swift XCode

ios - 访问 CoreData 属性的问题

ios - 如何添加联系人自定义应用程序帐户,如下图所示

ios - 取消按钮对 CNContactViewController 没有任何影响

iOS:从 CNContact 获取数字 key

ios - CNContactPickerViewController 仅检索选定的项目

swift - 请求访问地址簿时应用程序卡住