Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open link in UITextView within App

I'm trying to open a link that my UITextView recognizes within the app. I'm using the UITextView delegate method shouldInteractWithURL to achieve this.

My code seems to work fine for the in app loading of the url; however, it is still opening the link in Safari in addition to within the app. Is there any way to fix this?

func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {

    println("called")
    let webViewController = WebViewController()        
    webViewController.urlToLoad = URL

    if let navigationController = navigationController {
        println("navigating")
        navigationController.pushViewController(webViewController, animated: true)
        return true
    }
    else {
        return false
    }
}

Note that WebViewController is just a custom class that I made that displays a UIWebView as the whole screen. It has one property urlToLoad which is the url that it will load in the UIWebView.

I also assigned the delegate of the UITextView to the UIViewController implementing this delegate function already.

Does anyone know how to make the app stop opening safari?

like image 691
ad121 Avatar asked Jan 09 '23 01:01

ad121


1 Answers

The shouldInteractWithURL function should return true only if the link has to be opened up in Safari. If you are handling the link yourself you should return false. Check the changed line in the code below.

You can also use optional chaining instead of the if condition to call pushViewController

func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {

    let webViewController = WebViewController()        
    webViewController.urlToLoad = URL

    navigationController?.pushViewController(webViewController, animated: true)

    return false // Changed line.
}
like image 87
rakeshbs Avatar answered Jan 15 '23 11:01

rakeshbs