In my app, I have a string like:
"3022513240"
I want to convert this like:
(302)-251-3240
How can I solve this?
Method 1: Changing the Text Field Type from storyboard. Select the text field that you want to restrict to numeric input. Go to its attribute inspector. Select the keyboard type and choose number pad from there.
You should be able to use callNumber("7178881234") to make a call. it will give error as below; "This app is not allowed to query for scheme tel" for swift 3 and is these work on simulator or not? That code will not work in simulator. If you want to check it use a device.
Swift 4.2
Handles 10 and 11 digit phone numbers that may or may not already have formatting or non-digit characters in the string.
Will handle:
Result:
Code:
extension String {
/// Handles 10 or 11 digit phone numbers
///
/// - Returns: formatted phone number or original value
public func toPhoneNumber() -> String {
let digits = self.digitsOnly
if digits.count == 10 {
return digits.replacingOccurrences(of: "(\\d{3})(\\d{3})(\\d+)", with: "($1)-$2-$3", options: .regularExpression, range: nil)
}
else if digits.count == 11 {
return digits.replacingOccurrences(of: "(\\d{1})(\\d{3})(\\d{3})(\\d+)", with: "$1($2)-$3-$4", options: .regularExpression, range: nil)
}
else {
return self
}
}
}
extension StringProtocol {
/// Returns the string with only [0-9], all other characters are filtered out
var digitsOnly: String {
return String(filter(("0"..."9").contains))
}
}
Example:
let num = "1234567890"
let formatted = num.toPhoneNumber()
// Formatted is "(123)-456-7890"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With