繁体   English   中英

快速警报弹出进度栏

[英]Swift alert popup progress bar

我正在尝试实施一条警告消息,以显示下载期间的进度栏。

我发现以下代码:

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

任何帮助将不胜感激!

我确信进度条会有更好的答案...但是我的解决方案是知道必须如何加载项目(即某些变量“ 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的闭包。

目前,它在下面的代码中对我有用。 我声明为具有全局访问权限的vars的警报视图和进度视图,这样我就可以随着下载的进行更改进度,在下载任务完成后,我将关闭警报。

我正在执行以下操作:

  • 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
            }
        }


    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM