-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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