iFunnyVlogger iFunnyVlogger - 5 days ago 6
Swift Question

Open UIWebView Links In Safari

I have an iOS app using Swift 3. I have a uiwebview in this app. Whenever a user clicks on a link in the webview, it opens up inside the webview. I need it to where the links open up inside the Safari app on the iPhone. Here's the code:

class VideosViewController: UIViewController {

@IBOutlet var webView: UIWebView!

override func viewDidLoad() {
super.viewDidLoad()

var URL = NSURL(string: "http://example.com")

webView.loadRequest(NSURLRequest(url: URL! as URL) as URLRequest)


}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}


Can you please give me some code that I can enter? I'm new at coding, so thanks a lot.

UPDATE: Thanks to an answer I got some code, but I am getting a mime erroe on the line "webview.load(request)"

class VideosViewController : UIViewController, UIWebViewDelegate {

@IBOutlet weak var webView : UIWebView!

override func viewDidLoad() {
super.viewDidLoad()

guard let url = URL(string: "http://example.com") else { return }

let request = URLRequest(url: url)
webView.load(request)

}

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

if navigationType == .linkClicked {

guard let url = request.url else { return true }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
return false
}
return true
}


}

Wes Wes
Answer

Using UIWebView:

Make sure your view controller conforms to UIWebViewDelegate and then implement this method in the controller:

class VideosViewController : UIViewController, UIWebViewDelegate {

    @IBOutlet weak va webView : UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let url = URL(string: "http://example.com") else { return }

        let request = URLRequest(url: url)
        webView.load(request)

    }

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        if navigationType == .linkClicked {

            guard let url = request.url else { return true }
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
            return false
        }
        return true
    }
}

Using WKWebView:

Use a WKWebView instead of a UIWebView and make sure your controller conforms to the WKNavigationDelegate protocol. So your implementation would look something like the following:

class VideosViewController : UIViewController, WKNavigationDelegate {

    var webView : WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let url = URL(string: "http://example.com") else { return }

        webView = WKWebView(frame: self.view.frame)
        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.isUserInteractionEnabled = true
        webView.navigationDelegate = self

        self.view.addSubview(self.webView)

        let request = URLRequest(url: url)
        webView.load(request)

    }


    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        // Check if a link was clicked
        if navigationAction.navigationType == .linkActivated {

            // Verify the url
            guard let url = navigationAction.request.url else { return }
            let shared = UIApplication.shared

            // Check if opening in Safari is allowd
            if shared.canOpenURL(url) {

                // Ask the user if they would like to open link in Safari
                let alert = UIAlertController(title: "Open link in Safari?", message: nil, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (alert: UIAlertAction) -> Void in
                    // User wants to open in Safari
                    shared.open(url, options: [:], completionHandler: nil)
                }))
                alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))

                present(alert, animated: true, completion: nil)

            }
            decisionHandler(.cancel)
        }
        decisionHandler(.allow)
    }
}

This way, when a user clicks a link in the web view, they will be prompted with an alert that will ask them whether or not they would like to open it in Safari, and if it is allowed, Safari will launch and the link will be opened.

Comments