Reputation: 3682
I'm implementing a logic to check whether a contact exists or not in the contacts list and based upon this result I'm inserting the contact. My progress so far:
__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:@"[email protected]@" withContactPhone:str];
}
});
});
}
Now, the problem is after enumerating, the code under if (isExists == NO) fires several times and saving the contact multiple times.How do I stop it? My only need is if the contact exits then don't save it otherwise save it only one time. Any help will be appreciated.
Upvotes: 1
Views: 1970
Reputation: 5182
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;
}];
Upvotes: 1