我需要添加循环进度视图,以显示下载进度和其他多个任务完成状态,并希望显示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 ?
答案 0 :(得分:0)
您可以在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()
}
希望这对您有所帮助。