Reputation: 3742
I have an almost completely empty app consisting mainly of an WKWebView.
The usecase is basically a browser.
When clicking a link to a domain, that has an own app linked to the domain and whose app (linked via apple-app-site-association) is installed on the device, how can I stop the link being opened by the app (instead of my webview)?
I tried implementing methods of WKNavigationDelegate but was only able to cancel the navigation altogether.
What I want to happen:
What happens instead:
Upvotes: 1
Views: 931
Reputation: 1218
If the goal is to open any link in the same page, you can try the next implementation:
It worked for me (by the time I implemented it). Hopefully will work for you.
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView = WKWebView(frame: view.bounds)
webView.navigationDelegate = self
view.addSubview(webView)
if let url = URL(string: "https://www.example.com") {
webView.load(URLRequest(url: url))
}
}
// MARK: WKNavigationDelegate
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.targetFrame == nil || navigationAction.targetFrame?.isMainFrame == false {
// If the navigation action does not have a target frame or it is not the main frame,
// load the request in the same view by calling `load(_:)` on the WKWebView instance.
webView.load(navigationAction.request)
decisionHandler(.cancel)
} else {
// If the navigation action has a target frame and it is the main frame, allow the navigation to proceed.
decisionHandler(.allow)
}
}
}
Upvotes: 0