我实施了一个逻辑来检查联系人列表中是否存在联系人,并根据此结果插入联系人。到目前为止我的进展:
__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)下的代码会多次触发并多次保存联系人。如何阻止它?我唯一需要的是,如果联系人退出则不保存,否则只保存一次。任何帮助将不胜感激。
答案 0 :(得分:1)
替换代码中的以下部分,
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;
}];