繁体   English   中英

运行耗时的功能时如何显示活动指示器警报控制器?

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

我有Xcode 8.2,iOS 10,Swift 3。

在我的应用程序中,用户单击“开始处理”按钮,这启动了一项耗时的功能。 我希望有一个包含活动指示器的警报窗口。 但是,我看到的所有教程都只是向我展示了如何启动和停止它,而不是如何将其与函数运行异步地配对。

我的代码是这样的:

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)
}

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

谢谢您的帮助。

正如ebby94在他的评论中发布的链接所说,您应该真正避免在主线程上运行耗时的任务。 它冻结了UI,并且如果您花费太长时间,系统Springboard最终将挂起您的应用程序。

您实际上应该在后台任务上运行长时间运行的任务。 没有更多信息,我无法真正详细地解释这一点。

如果确定要在主线程上运行耗时的任务,则需要启动活动指示器旋转,然后在任务开始之前返回并给事件循环时间实际启动动画。 像这样:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM