2017-02-12 20 views
0

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

基本上,我不知道如何啓動和停止在正確的時間將活動的指標,我怎麼能顯示在這段時間警報控制器。

謝謝你的幫助。

+0

看看這個問題http://stackoverflow.com/questions/2919879/uiactivityindicator-not-working-properly – ebby94

+0

http://stackoverflow.com/questions/27033466/how-to-display-activity-indicator -in-center-of-uialertcontroller http://stackoverflow.com/questions/31408319/how-do-i-put-a-uiactivityindicatorview-in-a-uialertcontroller – 2017-02-12 02:37:46

+0

你可以使用NSTImer來設置你的活動指示器的時間開始和停止。 –

回答

2

正如他在評論中發佈的ebby94鏈接所說,你應該真的避免在主線程上運行耗時的任務。它凍結了用戶界面,如果你花費太長時間,系統Springboard最終會終止你的應用程序。

你應該真的在後臺任務上運行長時間運行的任務。沒有更多信息,我無法詳細解釋。

如果您決定在主線程上運行耗時的任務,則需要啓動活動指示器旋轉,然後返回並給出事件循環時間以在任務開始之前實際啓動動畫。例如:

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

Dispatch內部的代碼仍然會在主線程上運行,但首先運行循環將有機會啓動活動指示器。

+0

謝謝。在Swift 3中,它應該是'DispatchQueue.main.async',但是這個答案對我很有幫助。 – noblerare

+0

抱歉,錯字。我從記憶中輸入了它,顯然它錯了。很高興你能解決這個錯誤。 –