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