swift 2 NSURLSessionDownloadTask即使还有剩下的文件需要下载

时间:2016-05-21 07:54:57

标签: ios swift2 nsurlsessiondownloadtask

我正在尝试使用NSURLSessionDownloadTask下载30多个图像,问题是它不能完成下载所有内容。有时候,只下载了26张图片,但有时则更多或更少。我检查了我的网址并且所有网址都存在,但我不明白为什么要这样做。我已经尝试直接从服务器使用json url下载它崩溃,因为一个空的可选,这是由连接超时引起的。我明白这是因为这里的互联网并不稳定。但是当我尝试下载整个json文件并将其保存在我的文档目录中并尝试使用本地保存的json下载时,它不再崩溃,因为我不需要从中获取URL服务器。但是,会发生什么是我的进度条完成但并非所有图像都已下载。就像其他网址被忽略一样。

import UIKit

class ViewController: UIViewController, NSURLSessionDownloadDelegate {

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

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

var images = [String]()

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", "http://pillar.foundationu.com/wp-content/uploads/2016/03/Pasko-Maria-Katrina.jpg", "http://pillar.foundationu.com/wp-content/uploads/2016/03/Pastias-Grace.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()

        let file = FileHelperClass()

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

        var task: NSURLSessionDownloadTask!

        for s in file.parseJsonFromFile() /* fund returning images url */ {
            let url = NSURL(string: s)
            req = NSMutableURLRequest(URL:url!)
            task = self.session.downloadTaskWithRequest(req)
            self.task = task
            task.resume()

        }

        // Do something with the result

   self.endBackgroundUpdateTask(taskID)

    })

}

func beginBackgroundUpdateTask() -> UIBackgroundTaskIdentifier {
    return UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({})
}

func endBackgroundUpdateTask(taskID: UIBackgroundTaskIdentifier) {
    UIApplication.sharedApplication().endBackgroundTask(taskID)
}

    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)%"
    }
}


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!)
    images.append(downloadTask.response!.suggestedFilename!)
    print("\n \(images)")
  }
}

0 个答案:

没有答案