检测WKWebView何时完成加载

时间:2015-04-13 10:21:35

标签: ios swift wkwebview

我在iPad上的iOS8上运行WKWebView应用程序(标准iPad UserAgent:" Mozilla / 5.0(iPad; CPU OS 8_1_1,如Mac OS X)AppleWebKit / 600.1.4(KHTML,如Gecko)版本/ 8.0 Mobile / 12B436 Safari / 600.1.4")。我已经尝试了所有我能想到的代表和监听器,每次都尝试检测页面何时完成加载。这是问题所在:

  1. 打开您的WKWebView并转到Google。以下称为:

    _decidePolicyForNavigationAction
    _didStartProvisionalNavigation
    _ didFinishNavigation
    
  2. 在Google中输入“YouTube”:     只调用_decidePolicyForNavigationAction。没有didStartProvisionalNavigation或didFinishNavigation

  3. 点击Google内的YouTube。以下称为:

    _didStartProvisionalNavigation
    _decidePolicyForNavigationAction
    _ didFinishNavigation
    
  4. 从现在开始,在YouTube内没有任何内容被称为。点击YouTube视频,没有didStartProvisionalNavigation或didFinishNavigation。此外,不再调用webview.loading观察者。甚至decisionPolicyForNavigationAction也只是偶尔被调用。但是...... webView.backForwardList.currentItem 会在每次点击后更新,所以这必须检测页面何时完成加载?

  5. 此行为也发生在很多其他网站上(例如Vimeo)。我知道这种类型的网站每次都没有更新主框架,但缺乏检测何时加载已经开始/完成WKWebView当前状态的“限制”的能力?

    我想要实现的目标是:是否有其他方法可以检测导航是否已完成,每次在Java / Vimeo等Java移动网站中

    • 使用NSURLProtocol或类似的?
    • 或许是一种检测何时的方法 webView.backForwardList.currentItem是否已更新?

    感谢您的帮助。

2 个答案:

答案 0 :(得分:10)

我不确定在加载页面时你想要做什么,但希望观察这些属性可以帮助你:

webView.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)
webView.addObserver(self, forKeyPath: "loading", options: .New, context: nil)
webView.addObserver(self, forKeyPath: "title", options: .New, context: nil)
webView.addObserver(self, forKeyPath: "canGoBack", options: .New, context: nil)
webView.addObserver(self, forKeyPath: "canGoForward", options: .New, context: nil)

答案 1 :(得分:0)

如果有人正在寻找如何使用观察者的解决方案,这里是解决方案:

webView.addObserver(self, forKeyPath: "title", options: .new, context: nil);
webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil);
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil);

然后使用 observeValue 函数并编写一个 switch-case 或 if-else 来查找 keyPath

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "title" {
        print(change ?? "No title")
        if change != nil, let currentTitle = change?[.newKey] as? String {
            titleLabel.text = currentTitle
        }
    } else if keyPath == "loading" {
        print("Loading")
        reloadButton.setImage(#imageLiteral(resourceName: "cancel.png"), for: .normal)
    } else if keyPath == "estimatedProgress" {
        print(wkWebView.estimatedProgress);
        progressView.progress = Float(wkWebView.estimatedProgress)
    }
}

Here 我创建了一个演示项目来探索有关 WebKit WebView 的更多信息。