2016-09-29 79 views
0

我試圖在下載過程中實現顯示進度欄的警報消息。快速彈出警告彈出進度條

我發現這個代碼:

let alertView = UIAlertController(title: "Please wait", message: "Need to download some files.", preferredStyle: .Alert) 
alertView.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) 


presentViewController(alertView, animated: true, completion: { 
// Add your progressbar after alert is shown (and measured) 
let margin:CGFloat = 8.0 
let rect = CGRectMake(margin, 72.0, alertView.view.frame.width - margin * 2.0 , 2.0) 
let progressView = UIProgressView(frame: rect) 
progressView.progress = 0.5 
progressView.tintColor = UIColor.blueColor() 
alertView.view.addSubview(progressView) 
}) 

但我不知道如何更新處理,更重要的,當下載完成後如何從這個警報退出過程中的進展(progressView.progress)。

任何幫助將不勝感激!

回答

0

我確定有更好的答案進度條......但我的解決方案是知道如何可能項目必須加載(即一些變量「total_item」),增加完成的數量(numDownloaded)並計算百分比基於有多少人下載,然後更新百分比

駁回UIAlertController容易只需添加:。

let okAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: {action in self.dismiss(animated: true, completion: nil)}) 
alertView.addAction(okAction) 

這將增加一個「好」按鈕,將關閉該視圖控制器也許你。可以添加一個只在加載完成時啓用「OK」UIAlertAction的閉包。

+0

其實我只有項目要下載...但這是一個多部分HTTP POST,可能需要一些時間。我希望一旦HTTP請求完成(一旦收到結果),警報消息就會自動消失,我不希望最終用戶實際上單擊「確定」按鈕... – tiamat

+0

強制執行最終用戶保持在下載狀態屏幕上。如果您在[Ray Wenderlich's](https://www.raywenderlich.com/79149/grand-central-dispatch-tutorial-swift-part-1)博客上查看如何使用GCD,可能會更好,並且只需要注意在單獨的線程中下載。 – NonCreature0714

+0

我知道...但我需要填充一個UITableViewController從HTTP Post收到的數據我沒有選擇,否則最終用戶將需要拉tableView查看數據是最差的... – tiamat

0

目前它適用於我這樣的代碼在下面。我聲明爲具有全局訪問權限的警報視圖和進度視圖,這樣我可以在下載過程中更改進度,在下載任務完成後關閉警報。我正在執行以下內容; URLSessionDelegate,URLSessionTaskDelegate,URLSessionDownloadDelegate。爲了您的信息,我建你貼,因爲我還需要像這樣

var globalAlert: UIAlertController! //with global access 
var globalProgressView: UIProgressView! //with global access 

    //flags 
var downloading: Bool = false //true if we have a download in progress 
var globalAlertShowing = false //true if global alert is showing 

FUNC urlSession工作(_會議代碼:URLSession, downloadTask:URLSessionDownloadTask, didWriteData bytesWritten:Int64的, totalBytesWritten:Int64的, totalBytesExpectedToWrite:Int64){

if totalBytesExpectedToWrite > 0 { 
     let progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite) 
     print("Progress (ByteCountFormatter.string(fromByteCount: progress, countStyle: ByteCountFormatter.CountStyle.decimal))") 
     var humanReadableFileSize: String = ByteCountFormatter.string(fromByteCount: Int64(totalBytesWritten), countStyle: ByteCountFormatter.CountStyle.decimal) 
     print("total byte written: \(humanReadableFileSize)") 

     if(globalAlertShowing){ 
      DispatchQueue.main.async { 
       self.globalAlert.message = "\(humanReadableFileSize)" 
       self.globalProgressView.progress = progress 
      } 
     } 


    } 

}