Skip to content

Instantly share code, notes, and snippets.

@kotowo
Created June 13, 2024 23:14
Show Gist options
  • Save kotowo/8c64495d1fce9ee3aa05b20887192d61 to your computer and use it in GitHub Desktop.
Save kotowo/8c64495d1fce9ee3aa05b20887192d61 to your computer and use it in GitHub Desktop.
WKWebView の URL のリンクをクリックした時に外部のブラウザを起動
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
if let url = URL(string: "https://www.example.com") {
webView.load(URLRequest(url: url))
}
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.url, navigationAction.navigationType == .linkActivated, UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment