How to remove non numeric characters from phone number in objective-c?

Fernando Crespo picture Fernando Crespo · Feb 28, 2013 · Viewed 9.2k times · Source

This is my first attempt to make an ios app.

I'm using people picker to ask the user for a phone number, but when it retrieves with the code below, my NSString *phone apears like (0) 111192222-2222. I'm from Brazil and here the correct mask for mobile phone numbers is (01111) 92222-2222 (the 9 is optional, some numbers have others don't). How to fix this mask? Or remove it entirely?

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    ABMultiValueRef multiValue = ABRecordCopyValue(person, property);
    CFIndex index = ABMultiValueGetIndexForIdentifier(multiValue, identifier);
    NSString *phone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(multiValue, index);
    return NO;
}

Answer

Johan Kool picture Johan Kool · Feb 28, 2013

See this answer: https://stackoverflow.com/a/6323208/60488

Basically:

NSString *cleanedString = [[phoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789-+()"] invertedSet]] componentsJoinedByString:@""];

For your case you may want to remove the characters "-", "(" and ")" from the character set.