How to detect URLs, Addresses, Phone Numbers and Dates using NSDataDetector

Using NSDataDetector class we can detect URLs, addresses, phone numbers and dates inside any string.
Using below code snippet you can detect these and also find their range respectively.


let string = "This is an address PO Box 7775, San Francisco, CA. This is a url http:/
www.swiftdevcenter.com/. This is second url: https://www.google.com/. This is mobile number
+18987656789. This is a date 01/26/2019"

let detectorType: NSTextCheckingResult.CheckingType = [.address, .phoneNumber, .link, .date]
do {
    let detector = try NSDataDetector(types: detectorType.rawValue)
    let results = detector.matches(in: string, options: [], range: NSRange(location: 0, length:
string.utf16.count))
    
    for result in results {
        if let range = Range(result.range, in: string) {
            let matchResult = string[range]
            print("result: \(matchResult), range: \(result.range)")
        }
    }
    
} catch {
    print("handle error")
} 
The console log is below of above code:
result: PO Box 7775, San Francisco, CA., range: {19, 31}
result: http://www.swiftdevcenter.com/, range: {65, 30}
result: https://www.google.com/, range: {117, 23}
result: +18987656789, range: {164, 12}

Leave a Reply

Your email address will not be published. Required fields are marked *