David Seek
David Seek

Reputation: 17152

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.

Upvotes: 1

Views: 154

Answers (2)

xmhafiz
xmhafiz

Reputation: 3538

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

Upvotes: 4

Lou Franco
Lou Franco

Reputation: 89242

You are going to need to listen for any changes to the text view (via the delegate) and then run it through NSDataDetector yourself: https://developer.apple.com/reference/foundation/nsdatadetector

Upvotes: 1

Related Questions