Open Mobile Safari from a Link in a Webview

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

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

Open Mobile Safari from a Link in a WebView

Update:
So, as of iOS 6.0.2, there is still isn't a URL scheme specific to MobileSafari (see below). However, Federico Viticci has posted an interesting hack that will allow you to call Safari from Chrome for iOS. It's not as functional as a Chrome-to-Safari bookmarklet, but it does show it's possible to launch MobileSafari from Chrome for iOS.

Original Answer:
It turns out you can't open a link in Safari using just a URI scheme. Hyperlinks in other apps can be opened in safari using openURL (see other answers), but there is no scheme for MobileSafari itself (which you would need if you were to open a link in Safari using a hyperlink in Chrome or Opera for iOS).

Google Chrome has the following two URI schemes: googlechrome:// and googlechromes:// (for HTTPS) that work just as any other app-specific scheme (such as dayone://, things://, or sms://).



Related Topics



Leave a reply



Submit