ios - 如何在运行耗时函数时显示 Activity Indicator Alert Controller?

标签 ios swift swift3 uiactivityindicatorview

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

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

感谢您的帮助。

最佳答案

正如 ebby94 在他的评论中发布的链接所说,您应该真正避免在主线程上运行耗时的任务。它会卡住 UI,如果您花费的时间过长,系统 Springboard 最终会终止您的应用程序。

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

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

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

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

关于ios - 如何在运行耗时函数时显示 Activity Indicator Alert Controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42183478/

相关文章:

ios - Swift iOS 应用存档错误

swift - 正确释放嵌入在 subview 中的 NSViewController

ios - 如何根据设备更改导航栏的大小?

swift 错误 : failed to get module 'My_App' from AST context

ios - 如何使用 SwiftUI 调用电话

ios - 从 Swift 中的任意 anchor 呈现弹出窗口

ios - 在 Storyboard 中创建的 UIViewController 中动态调整 UITableView 的大小

swift - 点击单元格后返回到 UICollectionView 的相同滚动位置

ios - Swift 3.0 AVAudioPlayer 通过音乐播放音频

swift - 图像未显示在 uiimageview 中