Activity WKWebView 加载完成后指示器不会停止旋转

Activity Indicator won't stop spinning after WKWebView load finish

我是 Swift 和 iOS 开发的新手,非常感谢您对我的帮助!

我已经尝试了每个在线示例和本网站上的每个页面,但我无法让 Activity 指示器在页面完成加载到我的 WKWebview 后停止显示。

如有任何帮助,我们将不胜感激!谢谢!

import UIKit
import WebKit

class FirstViewController: UIViewController,     WKUIDelegate, WKNavigationDelegate {

@IBOutlet var webView: WKWebView!

@IBOutlet var activityIndicator: UIActivityIndicatorView!

override func viewDidLoad() {
    super.viewDidLoad()

    webView.uiDelegate = self

    activityIndicator.startAnimating()
    activityIndicator.isHidden = true
    activityIndicator.hidesWhenStopped = true

    let url = Bundle.main.url(forResource: "Web/bulk_material_table", withExtension: "html")!
    webView.loadFileURL(url, allowingReadAccessTo: url)
    let request = URLRequest(url: url)
    self.webView.load(request)


}

func showActivityIndicator(show: Bool) {
    if show {
        activityIndicator.startAnimating()
    } else {
        activityIndicator.stopAnimating()
    }
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    showActivityIndicator(show: false)
}

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    showActivityIndicator(show: true)
}

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    showActivityIndicator(show: false)
}
}

只需替换

webView.uiDelegate = self

webView.navigationDelegate = self

它会起作用,因为

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    showActivityIndicator(show: false)
}

WKNavigationDelegate的委托方法。