Hi Apple developers, I am very new to XCode and Swift, I am planning to build an app for iOS from a web. I tried to use WKWebView to handle the web , I managed to redirect some of the links to Safari, however some button/links didn't trigger .linkActivated function and encounter the error as "Your browser preventing this app to open “URL”.
If I copy the URL to Safari is able to open, I trying to research on web but can't find any related solution for my case.
Here is the code in my app:
import UIKit
import WebKit
import SafariServices
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Initialize WKWebView
let webConfiguration = WKWebViewConfiguration()
//enable javascript
webConfiguration.preferences.javaScriptEnabled = true
webView = WKWebView(frame: self.view.frame, configuration: webConfiguration)
webView.navigationDelegate = self
self.view.addSubview(webView)
// Load a web page as webview
if let url = URL(string: "https://myurl") {
let request = URLRequest(url: url)
webView.load(request)
}
//console log
webView.evaluateJavaScript("console.log('Button clicked!')") { result, error in
if let error = error {
print("Error executing JavaScript: \(error.localizedDescription)")
} else {
print("JavaScript result: \(String(describing: result))")
}
}
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.url, navigationAction.navigationType == .linkActivated {
// Check if URL is external and open it in Safari
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
decisionHandler(.cancel) // Prevent loading the link in the WebView
} else {
decisionHandler(.allow) // Allow loading if URL cannot be opened in Safari
}
} else {
decisionHandler(.allow) // Allow the WebView to load the URL normally
}
}
}