Mayur Tolani
Mayur Tolani

Reputation: 1487

How to open a link in UIWebView

I am having a chat application, which occasionally receives a link. On clicking that link, I can view the webpage in Safari, I would like to open that link in a UIWebview in my app instead.

I was going through this article, And its all good but it is giving in a hard coded link. I want to be able to open the link that user just clicked upon. whats the best way to achieve this?

Upvotes: 0

Views: 895

Answers (2)

thomas gotzsche
thomas gotzsche

Reputation: 387

Jus setup a delegate to the UITextView and implement this function:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    // open URL in UIWebView
}

Remember to extend the UITextViewDelegate and set the delegate to self:

@IBOutlet var textview: UITextView!
class SomeVC: UIViewController, UITextViewDelegate {
   override func viewDidLoad() {
    super.viewDidLoad()
    textview.delegate = self
   }
}

Upvotes: 0

Fangming
Fangming

Reputation: 25260

Basically, you need to first ask your textView to recognize urls

textView.text = "example www.google.com"
textView.isSelectable = true
textView.dataDetectorTypes = UIDataDetectorTypes.link

But then in delegate method shouldInteractWithURL, return false so that your URL is clickable but you will not jump to Safari.

extension ViewController: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        print(url)
        //load url to YOUR web view here!
        return false
    }
}

Don't forget to set delegate!

textView.delegate = self

Upvotes: 2

Related Questions