Как отследить прогресс и увеличить количество просмотров прогресса при работе с несколькими задачами? - PullRequest
1 голос
/ 27 марта 2019

Мне нужно добавить круговое представление прогресса, которое показывает ход загрузки и другие состояния завершения нескольких задач, и я хочу показать 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 ?

1 Ответ

0 голосов
/ 27 марта 2019

вы можете использовать этот код в методе 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::

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()
}

надеюсь, что это поможет вам.

...