我正在使用WKWebView的iOS应用程序,以及自定义导航按钮。我们发现在某些链接之后需要使用我们的“后退”按钮两次,因为第一次调用似乎只是重新加载当前页面。这在移动Safari中不会发生。
什么可能导致goBack()需要被调用两次以实际导航回一页,而它在Safari中正常工作?我可以在应用中进行更改以纠正问题吗?
注意:我无法更改网站的内容或结构,因此任何修复都必须在应用中。
更新 看来该网站正在使用JavaScript进行一些内容加载。当发生这种情况时,并不会调用observeValue方法,而且可能是罪魁祸首。
import UIKit
import WebKit
import SafariServices
class LandingPageViewController: UIViewController, SFSafariViewControllerDelegate, WKUIDelegate, WKNavigationDelegate {
@IBOutlet var urlNavigationItem: UINavigationItem!
@IBOutlet var backButton: UIBarButtonItem!
@IBOutlet var forwardButton: UIBarButtonItem!
@IBOutlet var reloadButton: UIBarButtonItem!
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView = WKWebView()
view.addSubview(webView)
webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil)
let request = URLRequest(url: url) //url is defined elsewhere
webView.navigationDelegate = self
webView.load(request)
webView.allowsBackForwardNavigationGestures = true
webView.uiDelegate = self
backButton.isEnabled = false
forwardButton.isEnabled = false
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if(keyPath == "loading"){
backButton.isEnabled = webView.canGoBack
forwardButton.isEnabled = webView.canGoForward
}
}
@IBAction func back(_ sender: UIBarButtonItem) {
webView.goBack()
}
@IBAction func forward(_ sender: UIBarButtonItem){
webView.goForward()
}
@IBAction func reload(_ sender: UIBarButtonItem) {
let request = URLRequest(url: webView.url!)
webView.load(request)
}
func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
// Custom logic here
}
}
答案 0 :(得分:1)
尝试使用以下委托方法,
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
decisionHandler(.allow)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
decisionHandler(.allow)
}
您已实施了一项但未调用decisionHandler(.allow)
答案 1 :(得分:0)
我面临着同样的问题。对我有用的是停止导航,然后返回。
func goBack() {
self.webView.stopLoading()
if (self.webView.canGoBack) {
self.webView.goBack()
return;
}
}