同时下载多个文件时的暂停和继续任务

时间:2019-02-19 08:50:16

标签: swift nsurlsession

我的应用看起来像这样。App Image 我的桌子上有歌曲,可以下载它们以及将其暂停和恢复。但是我对暂停和恢复有问题。例如,我单击下载Track01,然后暂停10%的下载。然后,我单击下载Track02,并暂停30%的下载。现在,我单击恢复下载Track01,他从30%恢复,但没有恢复10%。 Track02的任务替换Track01的任务。如何为每个音轨分别制定任务?我的下载代码如下:

class DownloadTracks: NSObject,URLSessionDownloadDelegate, URLSessionTaskDelegate, URLSessionDelegate  {

var task : URLSessionDownloadTask!
let configuration = URLSessionConfiguration.default
let operationQueue = OperationQueue.main
var session : URLSession!
var downloadTaskID : Int!
var progress : Float = 0.0


func downloadTask(url : URL) {
    session = URLSession.init(configuration: configuration, delegate: self, delegateQueue: operationQueue)
    task = session.downloadTask(with: url)
    task.resume()

    print("go download")
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    print("1111")
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    let documentaryDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let destenationURL = documentaryDirectoryURL.appendingPathComponent(downloadTask.description + ".mp3")
    print(destenationURL)

    do {
        try FileManager.default.moveItem(at: location, to: destenationURL)

    }
    catch let error as NSError {
        print(error.localizedDescription)
    }

}

func pauseDownload() {

    task.suspend()

}

func resumeDownload() {

    task.resume()
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    progress = Float (totalBytesWritten) / Float(totalBytesExpectedToWrite)
    print(progress)
} 
}

0 个答案:

没有答案