如何显示 Activity Indicator Alert Controller 而 运行 是一个耗时的函数?

How do I display an Activity Indicator Alert Controller while running a time-consuming function?

我有 Xcode 8.2,iOS 10,Swift 3.

在我的应用程序中,用户单击一个按钮 "Start Processing" 启动一个耗时的功能。我希望有一个包含 Activity 指标的警报 window。但是,我看到的所有教程都只向我展示了如何启动和停止它,而不是如何将它与函数的 运行 异步配对。

我的代码是这样的:

func doProcessing() {
    for (...) {
        timeConsumingFunction()
    }
}

// This function displays a setup which allows the user to manually kick off the time consuming processing.
func displaySetupScreen() {

    let alertController = UIAlertController(title: "Settings", message: "Please enter some settings.", preferredStyle: .alert)

    // ask for certain settings, blah blah.

    let actionProcess = UIAlertAction(title: "Process", style: .default) { (action:UIAlertAction) in
        //This is called when the user presses the "Process" button.
        let textUser = alertController.textFields![0] as UITextField;

        self.doProcessing()
        // once this function kicks off, I'd like there to be an activity indicator popup which disappears once the function is done running.
    }
    self.present(alertController, animated: true, completion: nil)


}

// this displays the actual activity indicator ... but doesn't work
func displayActivityIndicator() {
    // show the alert window box
    let alertController = UIAlertController(title: "Processing", message: "Please wait while the photos are being processed.", preferredStyle: .alert)

    let activityIndicator : UIActivityIndicatorView = UIActivityIndicatorView()
    activityIndicator.hidesWhenStopped = true
    activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
    activityIndicator.startAnimating()

    self.present(alertController, animated: true, completion: nil)
}

基本上,我不知道如何在正确的时间启动和停止 activity 指示器以及如何在这段时间内显示警报控制器。

感谢您的帮助。

正如 link ebby94 在他的评论中所说,你真的应该避免 运行 在主线程上执行 time-consuming 任务。它会冻结 UI,如果您花费的时间过长,系统 Springboard 最终会终止您的应用程序。

您确实应该 运行 您的 long-running 后台任务。如果没有更多信息,我真的无法详细解释。

如果您决定 运行 在主线程上完成您的 time-consuming 任务,那么您需要启动 activity 指标旋转,然后 return 并给出事件在任务开始之前实际开始动画的循环时间。像这样:

activityIndicator.startAnimating()
DispatchQueue.main.async {
  //Put your long-running code here
  activityIndicator.stopAnimating()
}

Dispatch 中的代码仍将在主线程上 运行,但首先 运行 循环将有机会启动 activity 指标。