Search code examples
iosnsmutablearraynsarrayaddressbook

How can I remove facebook contacts from array? Ios AddressBook


I'm using the address book, but do not want him to bring contacts from facebook. I made a if statement to filter, but I do not remove it from my array.

ABMultiValueRef emails  = ABRecordCopyValue(person, kABPersonEmailProperty);

    CFIndex numberOfEmails = ABMultiValueGetCount(emails);
    userDetail.allEmails = [@[] mutableCopy];
    for (CFIndex i = 0; i < numberOfEmails; i++) {

        NSString *email = CFBridgingRelease(ABMultiValueCopyValueAtIndex(emails, i));

        if ([email containsString:@"@facebook.com"]) {
            NSLog(@"remove emails: %@", userDetail.allEmails);

        }
        [userDetail.allEmails addObject:email];
    }

Solution


  • i use NSPredicate & NSCompoundPredicate for filtering.

     CFErrorRef *error = NULL;
            ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
            CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
            CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
            NSMutableArray *mylist = [[NSMutableArray alloc] initWithCapacity:numberOfPeople];
            for(int i = 0; i < numberOfPeople; i++) {
                ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
                NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
                NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
                ABMultiValueRef email = ABRecordCopyValue(person, kABPersonEmailProperty);
                for (CFIndex i = 0; i < ABMultiValueGetCount(email); i++) {
                    NSString *emailId = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(email, i);
                    NSDictionary *myObjlist = @{@"email":emailId,@"name":[NSString stringWithFormat:@"%@ %@",firstName,lastName]};
                    //NSLog(@"Name:%@ %@ : %@", firstName, lastName,myObjlist);
                    [mylist addObject:myObjlist];
    
                }
            }
            //NSLog(@"mylist : %@",mylist);
            NSPredicate *p = [NSPredicate predicateWithFormat:
                @"SELF['email'] CONTAINS '@facebook.com'"];
            NSPredicate *notFilter = [NSCompoundPredicate notPredicateWithSubpredicate:p];
            NSArray *res = [mylist filteredArrayUsingPredicate:notFilter];
            NSLog(@"awesome %@", res);
    

    let me know if you have any doubts .