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) | |
} | |
} | |
} |
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
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.