Swift - 实施全局 activity 指标

Swift - Implement global activity indicator

我目前正在尝试在 swift 中创建一个全局 activity 指标,每当对 api 进行提取时都会调用该指标。这个想法是 activity 指示器将出现在导航栏(导航视图控制器的子项)的左上角,并且在每个应用程序页面上都可用。

由于新帐户/低代表无法显示示例图片

我的 activity 指示器显示正确,我只是不确定如何在应用程序的任何页面上使用它 - 我考虑过扩展,但不确定是什么接近它的最好方法是。任何帮助将不胜感激。

Activity指标代码:

let activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
var activityItem = UIBarButtonItem()

func navBarActivity() {
    // Call navBarActivity() to start activity indicator
    // Use navigationItem.leftBarButtonItem = nil to stop activity indicator
    activityIndicator.startAnimating()
    activityIndicator.hidden = false

    self.activityItem = UIBarButtonItem(customView: activityIndicator)
    self.navigationItem.leftBarButtonItem = activityItem
}

我会推荐这样的扩展。

extension UIViewController {
    func displayNavBarActivity() {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: .White)
        indicator.startAnimating()
        let item = UIBarButtonItem(customView: indicator)

        self.navigationItem.leftBarButtonItem = item
    }

    func dismissNavBarActivity() {
        self.navigationItem.leftBarButtonItem = nil
    }
}

在 api 调用之前调用 self.displayNavBarActivity(),在 api 调用完成后调用 self.dismissNavBarActivity()

但是,我希望您检查 networkActivityIndicatorVisibleUIApplication。考虑使用此选项。

Specify YES if the app should show network activity and NO if it should not. The default value is NO. A spinning indicator in the status bar shows network activity. The app may explicitly hide or show this indicator.

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/#//apple_ref/occ/instp/UIApplication/networkActivityIndicatorVisible