-
-
Save kevenbauke/d449718a5f268ee843f286db88f137cc to your computer and use it in GitHub Desktop.
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) | |
} | |
} | |
} |
Hi, how do I check for URLs and application magnet links? My web application needs to launch another application via magnet links but the following code will handle links other than the default webview URL to open in browser or either just ignore. Thanks.
@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.
if components?.scheme == "magnet" {
// Do whatever you want.
}
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.
@Miztra cup that is fixed now. I removed the changes that were causing the error to appear.