David Seek David Seek - 7 days ago 6
Swift Question

How to call a function when an URL has been entered into a UITextView in Swift 3

I want to call a function the moment a URL has been entered into an UITextView. I know about

textView.dataDetectorTypes = .link
, but is there a Delegate or something that will be fired the moment a link has been recognized?

I have checked
UITextViewDelegate
, but I wasn't able to find anything.

What are my options? Help is very appreciated.

Answer

You can use UITextViewDelegate with shouldChangeTextIn method and check using NSDataDetector

Here is my working solution in Swift 3

extension ViewController: UITextViewDelegate {

    func checkURL(inputString: String) {
        let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
        let matches = detector.matches(in: inputString, options: [], range: NSRange(location: 0, length: inputString.utf16.count))

        for match in matches {
            let url = (inputString as NSString).substring(with: match.range)
            print(url)
        }
    }

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        checkURL(inputString: textView.text)
        return true
    }
}

Reference for NSDataDetector https://www.hackingwithswift.com/example-code/strings/how-to-detect-a-url-in-a-string-using-nsdatadetector