1

I created a new blank Single View Application with an UITextView that contains the link https://example.com.

When running my app, it auto detects that link and makes it blue. When clicking on this link, it gets opened in Apple Safari Browser.

How can I detect the link click and stop redirecting to Safari?

I tried the following code:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
    print("Link clicked!")
    return false
}

Unfortunately I'm not getting the print("Link clicked!") in console and it's still redirecting to Safari.

What am I doing wrong?

David
  • 2,898
  • 3
  • 21
  • 57

1 Answers1

3

This code will prevent the URL to get opened in Safari and will print the link in console:

import UIKit

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet var myTextViewAction: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        myTextViewAction.delegate = self
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        print("\nThis link was clicked: \(URL.absoluteString)\n")
        return false
    }
}
David
  • 2,898
  • 3
  • 21
  • 57
ppalancica
  • 4,236
  • 4
  • 27
  • 42