Open link in UITextView within App
Asked Answered
P

1

5

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?

Paneling answered 23/1, 2015 at 0:33 Comment(0)
J
12

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.
}
Joellyn answered 23/1, 2015 at 1:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.