使用swift在WKWebView上显示活动指示器

我正在处理以下代码,并尝试在页面加载时在视图中显示活动指示器。

我试图实现WKNavigationDelegate方法,但我失败了,因为没有显示。

对于如何解决这个问题,有任何的建议吗?

我没有在任何地方设置SupportWebView视图委托 ,但我不知道如何在swift中执行它。

import UIKit import WebKit class SupportWebView: UIViewController, WKNavigationDelegate { @IBOutlet var containerView : UIView? = nil var webView: WKWebView? override func loadView() { super.loadView() self.webView = WKWebView() self.view = self.webView } override func viewDidLoad() { super.viewDidLoad() var dataManager = DataManager.sharedDataManager() var url = dataManager.myValidURL var req = NSURLRequest(URL:url!) self.webView!.loadRequest(req) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } } 

如评论,您忘记设置webView委托:

 override func loadView() { super.loadView() self.webView = WKWebView() self.webView.navigationDelegate = self self.view = self.webView } 

您应该将委托方法用于所有其他目的,但密钥路径监视可以正常用于此目的。

这是一个工作正常的Swift 4实现。

 // Somewhere in your view controller private var loadingObservation: NSKeyValueObservation? private lazy var loadingIndicator: UIActivityIndicatorView = { let spinner = UIActivityIndicatorView() spinner.translatesAutoresizingMaskIntoConstraints = false spinner.color = .black return spinner }() override func viewDidLoad() { super.viewDidLoad() // Setup... loadingObservation = webView.observe(\.isLoading, options: [.new, .old]) { [weak self] (_, change) in guard let strongSelf = self else { return } // this is fine let new = change.newValue! let old = change.oldValue! if new && !old { strongSelf.view.addSubview(strongSelf.loadingIndicator) strongSelf.loadingIndicator.startAnimating() NSLayoutConstraint.activate([strongSelf.loadingIndicator.centerXAnchor.constraint(equalTo: strongSelf.view.centerXAnchor), strongSelf.loadingIndicator.centerYAnchor.constraint(equalTo: strongSelf.view.centerYAnchor)]) strongSelf.view.bringSubview(toFront: strongSelf.loadingIndicator) } else if !new && old { strongSelf.loadingIndicator.stopAnimating() strongSelf.loadingIndicator.removeFromSuperview() } } }