Report abuse

- (NSString *) findNameOfContactInAddressBook:(NSString *)phoneNumber {
	// Try to match based on the last 4 digits, then do a manual match, stripping all characters.
	// Have to do this since AddressBook doesn't normalize phone numbers.  WTF.
	NSString *lastFourDigits = [phoneNumber substringFromIndex:[phoneNumber length] - 4];

	ABAddressBook *AB = [ABAddressBook sharedAddressBook];
	ABSearchElement *pn = [ABPerson searchElementForProperty:kABPhoneProperty
                                 label:nil
                                   key:nil
                                 value:lastFourDigits
                            comparison:kABSuffixMatchCaseInsensitive];
	NSArray *peopleFound = [AB recordsMatchingSearchElement:pn];

	if ([peopleFound count] > 0) {
		for (int i = 0; i < [peopleFound count]; i++) {			
			ABPerson *person = [peopleFound objectAtIndex:0];
			ABMultiValue *phones = [person valueForProperty:kABPhoneProperty];

			for (int j = 0; j < [phones count]; j++) {
				if ([[self normalizePhoneNumber:[phones valueAtIndex:j]] isEqualToString:phoneNumber]) {
					return [NSString stringWithFormat:@"%@ %@", [person valueForProperty:kABFirstNameProperty], [person valueForProperty:kABLastNameProperty]];
				}
			}
		}
	}

	return phoneNumber;
}