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 NSStrin
I think there are ways to solve this:
textField:shouldChangeCharactersInRange:replacementString:
method,
check the replacement string if it is in the range of 0-9.Hope helps.
SWIFT 5.0 solution
let purePhoneNumber = phoneNumber.replacingOccurrences(of: "[^0-9]",
with: "",
options: .regularExpression)
If you want to leave +
sign in string, you can use regexp [^0-9+]
.
You can use few methods of NSString and NSMutableString as :
NSString *phone=@"(0) 111192222-2222";
//I'm from Brazil and here the correct mask for mobile phone numbers is (01111) 92222-2222
NSMutableString *editPhone=[NSMutableString stringWithString:[phone stringByReplacingOccurrencesOfString:@")" withString:@""]];
editPhone=[NSMutableString stringWithString:[editPhone stringByReplacingOccurrencesOfString:@" " withString:@""]];
[editPhone insertString:@") " atIndex:6];
NSLog(@"%@",editPhone);//(01111) 92222-2222
I would use Regular expression to validate the phone number instead of killing myself to make a custom keyboard, which functions can be changed by iOS updates. So, allow all characters and validate inside the code.
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.