簡體   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