gpt4 book ai didi

ios - 如何在处理多个任务时跟踪进度和进度 View 的增量计数?

转载 作者:行者123 更新时间:2023-11-28 07:29:25 25 4
gpt4 key购买 nike

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

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 ?

最佳答案

您可以在 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()
}

希望对您有所帮助。

关于ios - 如何在处理多个任务时跟踪进度和进度 View 的增量计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55377662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com