Search code examples
iosobjective-ciphoneaddressbook

iPhone AddressBook Search Using number


i am able to search a contact name using phone number.But there is some issues.Like if the number in the addressbook have countrycode with the number and if i search with only the number it returns emty value.So it can not search the proper way.Here is the code snipet i have done.

- (ABRecordRef)findRecord:(NSString *)phnNumber
{
if (phnNumber == nil)
    return nil;



CFErrorRef error = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);

if (!addressBook) {
    NSLog(@"null");
} else if (error) {
  NSLog(@"error %@",error);
}
// Requests access to address book data from the user
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {});


CFArrayRef all = ABAddressBookCopyArrayOfAllPeople(addressBook);


CFIndex n = ABAddressBookGetPersonCount(addressBook);
ABRecordRef record;

int count = 0;

for( int i = 0 ; i < n ; i++ )
{
    ABRecordRef ref = CFArrayGetValueAtIndex(all, i);

    ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);

    for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
    {

        CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phones, j);

        NSString *newPhoneNumber = (__bridge NSString *)phoneNumberRef;

        NSLog(@"%@",newPhoneNumber);

        if([newPhoneNumber isEqualToString:phnNumber])
        {
            record = ref;

            i=(int)n;
            count = 1;
        }
        CFRelease(phoneNumberRef);
    }

}

if(count != 1)
{
    ABRecordRef newPerson = ABPersonCreate();

    ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);

    ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFTypeRef)(phnNumber), kABHomeLabel, NULL);

    ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone,nil);
    CFRelease(multiPhone);
    record = newPerson;
}


return record;
}

and i am calling it like that for name:

ABRecordRef record = [self findRecord:@"Number_here"];

if(record){

    NSString *name =(__bridge NSString *)ABRecordCopyCompositeName(record);

    lbCalleName.text=name;
}

My problem is that- Suppose i have a contact and the phone number is like 8801723432323 and i am searching with this 01723432323 and above code returns emty.Here 88 is countrycode.Also i need to work opposite too.Suppose my given number have country code and no country code in address book.


Solution

  • Replace this line

     if([newPhoneNumber isEqualToString:phnNumber]) 
    

    withif ([newPhoneNumber containsString:phnNumber]) for iOS8 and later and
    NSRange range = [newPhoneNumber rangeOfString:phnNumber]; if (range.length != 0) for earlier devices. containsString: is introduced in iOS8.