Created
June 13, 2024 23:14
-
-
Save kotowo/8c64495d1fce9ee3aa05b20887192d61 to your computer and use it in GitHub Desktop.
WKWebView の URL のリンクをクリックした時に外部のブラウザを起動
This file contains hidden or 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, 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