Help with links in WebViews.

I have a webview in my app. Whenver the user clicks on a link inside the webview, it opens the link inside the webview. I want it where the link gets opened in the safari app. This is an iOS app btw. Can you please help me do this? Here's the code:


import UIKit
class FirstViewController: UIViewController {
   
    @IBOutlet var webView: UIWebView!
   
    override func viewDidLoad() {
        super.viewDidLoad()
       
        var URL = NSURL(string: "http:/
       
        webView.loadRequest(NSURLRequest(url: URL! as URL) as URLRequest)
       
       
    }
   
   
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        /
    }
   
}

Replies

Unless you have specific reasons to stick with UIWebView, I strongly recommend you adopt the more modern WKWebView.

In WKWebView you can set a navigation delegate that the web view calls as part of the navigation process. Two of those delegate callbacks —

webView(_:decidePolicyForNavigationAction:decisionHandler:)
and
webView(_:decidePolicyForNavigationResponse:decisionHandler:)
— allow you to override navigation policy. You can implement one of these to cancel the navigation and then open the URL in Safari by UIApplication’s
openURL(_:)
method.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Ok, is there any way to do it with a webview? I am very, very new to coding, and I'm still very much learning. 🙂

UIWebView has a delegate that has similar, although less capable, facilities.

However, if you’re just starting out with web views, you should use WKWebView; WKWebView is the future of web views, while UIWebView is very much the past.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Ok, I'll use WKWebView, what is the code I need to add?

what is the code I need to add?

To do what? Set up a web view? Or catch a link?

Here’s some code from my WKWebView test app that sets up the web view.

class WKWebViewController : UIViewController, WKNavigationDelegate {

    var webView: WKWebView { return self.view as! WKWebView }

    override func loadView() {
        let config = WKWebViewConfiguration()
        let webView = WKWebView(frame: CGRect.zero, configuration: config)
        webView.navigationDelegate = self
        self.view = webView
    }

    …
}

I don’t have the code handy for catching link requests, but it should just be a matter of implementing the delegate methods I described above.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"