Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force any links clicked within a WebView to open in Safari?

I have a WebView in my application and I would like any links clicked within the WebView to open in Safari (instead of the WebView itself).

I am developing the application in Swift.

What is the best method to do this?

like image 602
Kian Cross Avatar asked Feb 18 '15 01:02

Kian Cross


People also ask

Is WebView allowed in iOS?

It was released in iOS 2.0, and has been deprecated as of 8.0. UIWebView is deprecated. New apps using this control will not be accepted into the App Store as of April 2020, and apps updates using this control will not be accepted by December 2020.

Which browser is used in iOS WebView?

Safari browser installed in iOS & webview browser (if safari) are same or there are difference?

What does Safari WebView mean?

The “WebView” is the window through which your device displays these web pages. (from Human Element — Webview strategy for iOs and Android) Your WebView stands in place of a traditional browser. In the case of iOS, WK WebView does a fair job at replicating the user experience of Safari.

Does WKWebView use Safari?

WKWebView - This view allows developers to embed web content in your app. You can think of WKWebView as a stripped-down version of Safari. It is responsible to load a URL request and display the web content. WKWebView has the benefit of the Nitro JavaScript engine and offers more features.


1 Answers

This is done essentially the same way in Swift as in Obj-C:

First, declare that your view controller conforms to UIWebViewDelegate

class MyViewController: UIWebViewDelegate

Then implement webViewShouldStartLoadingWithRequest:navigationType: in your View Controller:

// Swift 1 & 2
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    switch navigationType {
    case .LinkClicked:
        // Open links in Safari
        UIApplication.sharedApplication().openURL(request.URL)
        return false
    default:
        // Handle other navigation types...
        return true
    }
}

// Swift 3
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    switch navigationType {
    case .linkClicked:
        // Open links in Safari
        guard let url = request.url else { return true }

        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            // openURL(_:) is deprecated in iOS 10+.
            UIApplication.shared.openURL(url)
        }
        return false
    default:
        // Handle other navigation types...
        return true
    }
}

Finally, set your UIWebView's delegate, e.g., in viewDidLoad or in your Storyboard:

webView.delegate = self
like image 150
Ronald Martin Avatar answered Oct 02 '22 18:10

Ronald Martin