Swift2 在swift 2中一批下载多个文件

Swift2 在swift 2中一批下载多个文件,swift2,ios9,nsurlsessiondownloadtask,Swift2,Ios9,Nsurlsessiondownloadtask,我正在尝试下载多个图像,结果是它一个接一个地下载,有没有办法将多个文件作为一个文件下载?我想做的是,我不希望进度视图跟踪每个文件的进度,而是希望它作为一个整体跟踪所有文件 import UIKit class ViewController: UIViewController, NSURLSessionDownloadDelegate { @IBOutlet weak var progressBar: UIProgressView! @IBOutlet weak var progressCo

我正在尝试下载多个图像,结果是它一个接一个地下载,有没有办法将多个文件作为一个文件下载?我想做的是,我不希望进度视图跟踪每个文件的进度,而是希望它作为一个整体跟踪所有文件

import UIKit

class ViewController: UIViewController, NSURLSessionDownloadDelegate {


@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var progressCount: UILabel!

var task : NSURLSessionTask!

var pics = ["http://pillar.foundationu.com/wp-content/uploads/2016/03/banner.jpg", "http://pillar.foundationu.com/wp-content/uploads/2016/03/Abad-Edmerl.jpg", "http://pillar.foundationu.com/wp-content/uploads/2016/03/Abellana-Deniz-Dawn-1.jpg", "http://pillar.foundationu.com/wp-content/uploads/2016/03/Abequibel-Arneth.jpg", "http://pillar.foundationu.com/wp-content/uploads/2016/03/Abilla-Harriette.jpg"]

var counter:Float = 0.0 {

    didSet {
        let fractionalProgress = Float(counter) / 100.0
        let animated = counter != 0

        progressBar.setProgress(fractionalProgress, animated: animated)
        progressCount.text = ("\(counter)%")
    }
    //The didSet is called immediately after the new value is stored. The fractionalProgress constant keeps track of the progress.
}

lazy var session : NSURLSession = {
    let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
    config.allowsCellularAccess = false
    let session = NSURLSession(configuration: config, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
    return session
    }()

override func viewDidLoad() {
    progressBar.setProgress(0.0, animated: true)  //set progressBar to 0 at start
}

@IBAction func doElaborateHTTP (sender:AnyObject!) {

    progressCount.text = "0%"
    if self.task != nil {
        return
    }
   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {

        let taskID = self.beginBackgroundUpdateTask()

        var url = NSURL!()
        var req = NSMutableURLRequest()

        for s in self.pics {
            url = NSURL(string: s)
            req = NSMutableURLRequest(URL:url)
            let task = self.session.downloadTaskWithRequest(req)
            self.task = task
            task.resume()
        }

        // Do something with the result

   self.endBackgroundUpdateTask(taskID)

    })

}

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
    print("downloaded \(100*writ/exp)")

    dispatch_async(dispatch_get_main_queue(), {
        self.counter = Float(100*writ/exp)
        return
    })
}

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
    // unused in this example
}

func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
    print("completed: error: \(error)")
}

// this is the only required NSURLSessionDownloadDelegate method

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {

    print(downloadTask.response!.suggestedFilename!)

  }
}

您可以在分数金额(例如:0.15)和百分比(15)之间来回转换。不要那样做。使用百分比进行显示。将所有计算结果保留为小数

试试这个:

var taskProgress = [NSURL: (written: Int64, expected: Int64)]()    

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
    dispatch_async(dispatch_get_main_queue()) {
        self.taskProgress[downloadTask.originalRequest!.URL!] = (writ, exp)

        // Update your views, you may separate it into a different function
        let totalWritten = self.taskProgress.reduce(0) { $0 + $1.1.written }
        let totalExpected = self.taskProgress.reduce(0) { $0 + $1.1.expected }
        let progress = Float(totalWritten) / Float(totalExpected)

        self.progressBar.setProgress(progress, animated: true)
        self.progressCount.text = "\(progress * 100)%"
    }
}

您可以在分数金额(例如:0.15)和百分比(15)之间来回转换。不要那样做。使用百分比进行显示。将所有计算结果保留为小数

试试这个:

var taskProgress = [NSURL: (written: Int64, expected: Int64)]()    

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
    dispatch_async(dispatch_get_main_queue()) {
        self.taskProgress[downloadTask.originalRequest!.URL!] = (writ, exp)

        // Update your views, you may separate it into a different function
        let totalWritten = self.taskProgress.reduce(0) { $0 + $1.1.written }
        let totalExpected = self.taskProgress.reduce(0) { $0 + $1.1.expected }
        let progress = Float(totalWritten) / Float(totalExpected)

        self.progressBar.setProgress(progress, animated: true)
        self.progressCount.text = "\(progress * 100)%"
    }
}

谢谢,我会试试这个。如果我只有很少的图片,它不会有问题,但是当我有很多图片时,在我的例子38中,它不会下载所有的东西。它会在某个图像上随机停止并完成下载。谢谢,我会尝试一下。如果我只有很少的图像,它不会有问题,但是当我有很多图像时,在我的例子38中,它不会下载所有的图像。它会随机停止并在某个图像处完成下载。