NSDataDetector
There are many application that extracting specific desired information from a string like date, url, link, address, number and many more. Using this specific desired information we can perform many useful action like create a event, open a url, save a contact number, navigate to particular address.
Example
The NSDataDetector
class can match dates, addresses, links, phone numbers and transit information. NSDataDetector
will be return one of the data detectors type, depending on the type of result being returned and they may have different properties. For example, Result of type link have have a url, result of type date have a date, timezone, and duration.
Example
This code creates a data detector that will find Date from text view.
// Create data detector
let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
// Find date from textView
if let matches = detector?.matches(in: textView.text!, options: [], range: NSRange(location: 0, length: textView.text!.utf16.count)) {
for match in matches {
// Check for result type
if match.resultType == .date {
let datefromatter = DateFormatter()
datefromatter.dateStyle = .medium
let alertController = UIAlertController(title: datefromatter.string(from: match.date!), message: "Create a plan", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
}
References :-
https://developer.apple.com/documentation/foundation/nsdatadetector