Tâche
Passer un appel avec validation du numéro de téléphone
Détails
Xcode 9.2, Swift 4
Solution
extension String {
enum RegularExpressions: String {
case phone = "^\\s*(?:\\+?(\\d{1,3}))?([-. (]*(\\d{3})[-. )]*)?((\\d{3})[-. ]*(\\d{2,4})(?:[-.x ]*(\\d+))?)\\s*$"
}
func isValid(regex: RegularExpressions) -> Bool {
return isValid(regex: regex.rawValue)
}
func isValid(regex: String) -> Bool {
let matches = range(of: regex, options: .regularExpression)
return matches != nil
}
func onlyDigits() -> String {
let filtredUnicodeScalars = unicodeScalars.filter{CharacterSet.decimalDigits.contains($0)}
return String(String.UnicodeScalarView(filtredUnicodeScalars))
}
func makeAColl() {
if isValid(regex: .phone) {
if let url = URL(string: "tel://\(self.onlyDigits())"), UIApplication.shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
}
}
}
Usage
"+1-(800)-123-4567".makeAColl()
Échantillon pour test
func test() {
isPhone("blabla")
isPhone("+1(222)333-44-55")
isPhone("+42 555.123.4567")
isPhone("+1-(800)-123-4567")
isPhone("+7 555 1234567")
isPhone("+7(926)1234567")
isPhone("(926) 1234567")
isPhone("+79261234567")
isPhone("926 1234567")
isPhone("9261234567")
isPhone("1234567")
isPhone("123-4567")
isPhone("123-89-01")
isPhone("495 1234567")
isPhone("469 123 45 67")
isPhone("8 (926) 1234567")
isPhone("89261234567")
isPhone("926.123.4567")
isPhone("415-555-1234")
isPhone("650-555-2345")
isPhone("(416)555-3456")
isPhone("202 555 4567")
isPhone("4035555678")
isPhone(" 1 416 555 9292")
}
private func isPhone(_ string: String) {
let result = string.isValid(regex: .phone)
print("\(result ? "✅" : "❌") \(string) | \(string.onlyDigits()) | \(result ? "[a phone number]" : "[not a phone number]")")
}
Résultat