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?
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.
Safari browser installed in iOS & webview browser (if safari) are same or there are difference?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With