URLSession不能连续下载

时间:2017-01-31 02:34:03

标签: swift nsurlsession

我正在尝试创建一个串行URLSession,以便我可以在串行队列中下载较大的文件。我一直在忙着这一天,我变得越来越困惑。

我当前的问题是如何让我的下载顺序发生?

到目前为止,我已经将文件下载到我想要的目录,并可以通过委托方法打印文件的进度。问题是,如果我下载超过1个文件,它们会同时发生,这不是我之后的事情。

我认为通过将delegateQueue声明为nil,这将实现吗?

lazy var downloadsSession: Foundation.URLSession = {
    let configuration = URLSessionConfiguration.background(withIdentifier: "urlSessionConfig")
    let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    return session
}()

接下来,启动下载和委派功能的功能:

func startDownload(urlString: String, block: @escaping (_ downloading: Bool, _ url: String) -> Void) {

    let download = Download(url: urlString)
    let url =  URL(string: urlString)
    download.downloadTask = downloadsSession.downloadTask(with: url!)
    download.downloadTask!.resume()
    download.isDownloading = true
    activeDownloads[download.url] = download

    if download.isDownloading == true {
        block(true, urlString)
    }
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {

    if (downloadTask.originalRequest?.url?.absoluteString) != nil {

        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let cachesDirectory: String = path[0]
        let fileName  = URL(string: (downloadTask.originalRequest?.url?.absoluteString)!)?.lastPathComponent
        let destinationURL = URL(fileURLWithPath: cachesDirectory.appendingFormat("/Parse/PFFileCache/\(fileName!)"))


        print(destinationURL)

        // remove temp file
        let fileManager = FileManager.default
        do {
            try fileManager.removeItem(at: destinationURL)
        } catch {
            // doesn't exist
        }
        do { // move to destinationURL
            try fileManager.copyItem(at: location as URL, to: destinationURL)
        } catch let error as NSError {
            print("Could not copy file to disk: \(error.localizedDescription)")
        }


        // remove the url from activeDownloads array
        if let url = downloadTask.originalRequest?.url?.absoluteString {
            activeDownloads[url] = nil
            self.outerCollectionView.reloadData()
        }
    }
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {


    if let downloadUrl = downloadTask.originalRequest?.url?.absoluteString,
        let download = activeDownloads[downloadUrl] {
        download.progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)
        //let totalSize = ByteCountFormatter.string(fromByteCount: totalBytesExpectedToWrite, countStyle: ByteCountFormatter.CountStyle.binary)
        print("\(download) \(download.progress)")
    }
}

0 个答案:

没有答案