Skip to content

Instantly share code, notes, and snippets.

@mrcgrtz
Last active August 11, 2019 14:29
Show Gist options
  • Save mrcgrtz/15683d746490c7a8c9a0f537732215b2 to your computer and use it in GitHub Desktop.
Save mrcgrtz/15683d746490c7a8c9a0f537732215b2 to your computer and use it in GitHub Desktop.
Swift 3 Extension for opening target="_blank" and mailto:/tel: links in native iOS apps
import UIKit
import WebKit
class ViewController: UIViewController {
var webView: WKWebView = WKWebView() {
didSet {
webView.navigationDelegate = self
webView.uiDelegate = self
}
}
// MARK: - Override functions
override func loadView() {
super.loadView()
self.webView.navigationDelegate = self
self.webView.uiDelegate = self
}
}
extension ViewController: WKNavigationDelegate, WKUIDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if webView != self.webView {
decisionHandler(.allow)
return
}
let app = UIApplication.shared
if let url = navigationAction.request.url {
// handle target="_blank"
if navigationAction.targetFrame == nil {
if app.canOpenURL(url) {
app.openURL(url)
decisionHandler(.cancel)
return
}
}
// handle phone and email links
if url.scheme == "tel" || url.scheme == "mailto" {
if app.canOpenURL(url) {
app.openURL(url)
decisionHandler(.cancel)
return
}
}
decisionHandler(.allow)
}
}
}
@gitothy
Copy link

gitothy commented Aug 10, 2019

Do you use it in a Swift 3 project or in a newer version of Swift? Actually I too had some (yet unresolved) issues using this extension in Swift 5.

It's the very latest version of Xcode so Swift 5. Your code does work to open a blank webview window but I can't get it to load a specific web page. It's reporting the openurl command is depreciated but I assume it still works. I've been struggling to get any code to treat links that are target="_blank" to open in safari rather than the app and I thought I'd hit the jackpot with this one but no joy.

@mrcgrtz
Copy link
Author

mrcgrtz commented Aug 11, 2019

Sorry. :-( I’m currently not actively working on a Swift project, but AFAIK I had the same issue in my last Swift 5 project while it stll worked in an older Swift 3 project. I’ll look into it in the next week or so.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment