-
-
Save fitomad/63bf81df7e30ba5ffa0d0c12f7176183 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// Texto de pruebas | |
let phoneNumbers = [ | |
"adfadf 677 111 222 adadf", | |
"asdfasdf adsf as df 677111222 sdf asdf adasa", | |
"asd asd ads 677 11 12 22", | |
"asd asd ads 677 1112 22", | |
"asdasds -- +34 677 111 22 asdsad", | |
"asdasd -- asdad +34677111222 adas", | |
" asdasd asdasd 00677111222 asdsdsa", | |
"1-(800)-345-7777", | |
"asda asd as d 1(800)3458888 zz", | |
"Esto no es un teléfono...", | |
"Pero aquí si hay uno 1-(800)-345-9999 al que llamaré después. Justo antes de llamar al +34 91 444 99 88" | |
] | |
// Así es como se buscan números de teléfono en un String | |
if let phoneDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue) | |
{ | |
// Vamos a buscar teléfonos en cada uno de los `String` del array de pruebas | |
phoneNumbers.forEach({ (phoneNumber: String) -> Void in | |
// Creamos un rango para que NSDataDetector separa donde tiene que buscar. | |
// En este caso es en la casdena completa | |
let range = NSRange(location: 0, length: phoneNumber.count) | |
// La función `matches` nos devuelve las ocurriencias dentro de la cadena, si las hubiera | |
let results = phoneDetector.matches(in: phoneNumber, options: .reportCompletion, range: range) | |
// Vamos a ver qué hemos encontrado | |
results.forEach({ | |
// A `NSTextCheckingResult` le pregunto si tiene algún teléfono | |
if let phoneNumber = $0.phoneNumber | |
{ | |
// Y si lo tiene lo muestro | |
print(phoneNumber) | |
} | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment