首页 > 解决方案 > 处理多个任务时如何跟踪进度和增加进度视图的计数?

问题描述

我需要添加显示下载进度和其他多个任务完成状态的循环进度视图,并希望显示 100% 完成并在所有任务完成后隐藏进度视图。例如。

func downloadAndProcessImages(imagesArray: [URL]){

downloadimages()
resizeImages()
addToDB()

}


func downloadimage(){

for image in imagesArray{

saveImaege()

}

}

func addToDB(){

// db tasks
}



So where to increment the count / progress of the progressview , when you have multiple tasks ?

标签: iosswiftprogress-bardownloaduiprogressview

解决方案


您可以在 viewWillAppear 方法中使用此代码:

  DownloadManager.shared.onProgress = { (progress) in
      OperationQueue.main.addOperation {
          self.hud_download.show(in: self.view)
          self.hud_download.detailTextLabel.text = "0%"
           self.hud_download.textLabel.text = "Downloading"
                var progress = Int(round(progress * 100))
                self.hud_download.progress = Float(progress)
                self.hud_download.detailTextLabel.text = "\(progress)%"

                if progress == 100{
                    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
                        UIView.animate(withDuration: 0.1, animations: {
                            self.hud_download.textLabel.text = "Download completed"
                            self.hud_download.detailTextLabel.text = nil
                            self.hud_download.indicatorView = JGProgressHUDSuccessIndicatorView()
                        })
                        self.hud_download.dismiss(afterDelay: 1.0)
     }
}

hud_download 是:

let hud_download = JGProgressHUD(style: .dark)

您必须在 ViewController 中创建

& DownloadManager 类是:

 import Foundation

 class DownloadManager : NSObject, URLSessionDelegate, URLSessionDownloadDelegate {

static var shared = DownloadManager()
var destinationFileUrl : URL? = nil
var file_name = String()
var file_extension = String()

typealias ProgressHandler = (Float) -> ()

var onProgress : ProgressHandler? {
    didSet {
        if onProgress != nil {
            let _ = activate()
        }
    }
}

override private init() {
    super.init()
}

func activate() -> URLSession {
    let config = URLSessionConfiguration.default

    // Warning: If an URLSession still exists from a previous download, it doesn't create a new URLSession object but returns the existing one with the old delegate object attached!
    return URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
}

private func calculateProgress(session : URLSession, completionHandler : @escaping (Float) -> ()) {
    session.getTasksWithCompletionHandler { (tasks, uploads, downloads) in
        let progress = downloads.map({ (task) -> Float in
            if task.countOfBytesExpectedToReceive > 0 {
                return Float(task.countOfBytesReceived) / Float(task.countOfBytesExpectedToReceive)
            } else {
                return 0.0
            }
        })
        completionHandler(progress.reduce(0.0, +))
    }
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {

    if totalBytesExpectedToWrite > 0 {
        if let onProgress = onProgress {
            calculateProgress(session: session, completionHandler: onProgress)
        }
        let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
        debugPrint("Progress \(downloadTask) \(progress)")

    }
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    print("Downlaod Finished")
    // download finished.do what you want
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {

    print("Task completed: \(task), error: \(error)")
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
    // unused in this example
}

func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {

    downloadFinished = false
    isRedirected = true
    Functions.functions.resetDefaults()

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRedirected"), object: nil)
}

}

只需创建 DownloadManager.swift 文件并粘贴代码。

并使用此方法进行下载,并且一切正常。

    func dl(file_name : String ,file_extension : String, file_path : String) {
    // for saving in device
    let documentsUrl:URL =  (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL?)!
    DownloadManager.shared.destinationFileUrl = documentsUrl.appendingPathComponent(file_name)
    DownloadManager.shared.file_name = file_name
    DownloadManager.shared.file_extension = file_extension
    let fileURL = URL(string: file_path)
    var request = URLRequest(url:fileURL!)
    // you can set request header by request.allHTTPHeaderFields
    let task = DownloadManager.shared.activate().downloadTask(with: request)
    task.resume()
}

希望对您有所帮助。


推荐阅读