Last active
June 21, 2022 17:13
-
-
Save kevenbauke/d449718a5f268ee843f286db88f137cc to your computer and use it in GitHub Desktop.
WKWebView open links in Safari
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 WebKit | |
class ViewController: UIViewController { | |
// Connect the webView from the StoryBoard. | |
@IBOutlet weak var webView: WKWebView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Get the path of the index.html which is part of the Xcode project (resp. in the main bundle). | |
guard let htmlPath = Bundle.main.path(forResource: "index", ofType: "html") else { | |
return | |
} | |
// Create an URL to load it in the webView. | |
let url = URL(fileURLWithPath: htmlPath) | |
let request = URLRequest(url: url) | |
webView.navigationDelegate = self | |
webView.load(request) | |
} | |
} | |
extension ViewController: WKNavigationDelegate { | |
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { | |
// Check for links. | |
if navigationAction.navigationType == .linkActivated { | |
// Make sure the URL is set. | |
guard let url = navigationAction.request.url else { | |
decisionHandler(.allow) | |
return | |
} | |
// Check for the scheme component. | |
let components = URLComponents(url: url, resolvingAgainstBaseURL: false) | |
if components?.scheme == "http" || components?.scheme == "https" { | |
// Open the link in the external browser. | |
UIApplication.shared.open(url) | |
// Cancel the decisionHandler because we managed the navigationAction. | |
decisionHandler(.cancel) | |
} else { | |
decisionHandler(.allow) | |
} | |
} else { | |
decisionHandler(.allow) | |
} | |
} | |
} |
I tried the method, but I'm not sure why if I use the code, it'll say WebPageProxy::didFailProvisionalLoadForFrame: frameID=575, domain=NSURLErrorDomain, code=-999
when the code was set like this:
if components?.scheme == "roblox-player" {
decisionHandler(.allow)
}
I think the error was dedicated to the custom scheme, because if I use webview.uiDelegate
(which doesn't handle external links) the error doesn't appear.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@raymond-1227 if you want want to detect magnet-links you can use a similar approach as how this code detects the links. You can use the scheme attribute of the URLComponent.