Skip to content

Instantly share code, notes, and snippets.

@ilyaashapatov
Forked from mrcgrtz/WKWebViewExtension.swift
Created November 14, 2018 14:52
Show Gist options
  • Save ilyaashapatov/a9f3f7a49149b2c8559f768c5fd5c415 to your computer and use it in GitHub Desktop.
Save ilyaashapatov/a9f3f7a49149b2c8559f768c5fd5c415 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)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment