1

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

__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)下的代码会触发多次并多次保存联系人。如何停止它?我唯一需要的是如果联系人退出然后不要保存它,否则只保存一次。任何帮助将不胜感激。

4

1 回答 1

1

replace the below part in your code,

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;

}];
于 2016-07-19T09:44:54.710 回答