简体   繁体   中英

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?

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

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
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM