Swift警告弹出进度条

时间:2016-09-29 20:13:40

标签: ios swift

我试图在下载过程中实现显示进度条的警告消息。

我找到了这段代码:

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),更重要的是如何在下载完成时退出此警报。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分: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)

这将添加一个"好的"按钮,将关闭视图控制器。也许你可以添加一个只能启用" Okay"负载完成时的UIAlertAction。

答案 1 :(得分: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(_ session: 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
            }
        }


    }

}