Last active
August 11, 2019 14:29
-
-
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
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
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.