【发布时间】:2018-08-08 08:06:54
【问题描述】:
我有部分和单元格的集合视图。
我使用此代码下载文件:
let sessionConfig = URLSessionConfiguration.background(withIdentifier: "com.example.DownloadTaskExample.background")
backgroundSession = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: OperationQueue())
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let url = URL(string: "link")!
let downloadTaskLocal = self.backgroundSession.downloadTask(with: url)
self.allDownloadTasks.append(downloadTaskLocal) // Add a new task to the array
downloadTaskLocal.resume()
}
func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64){
DispatchQueue.main.async(execute: {() -> Void in
if let visibleIndexPath = self.collectionView?.indexPathsForVisibleItems {
for visibleIndexPath in visibleIndexPath {
if (downloadTask.currentRequest?.url?.lastPathComponent == "\(visibleIndexPath.section)\(visibleIndexPath.row).zip") {
self.progressOfDownload.append("\(Int(CGFloat(totalBytesWritten) / CGFloat(totalBytesExpectedToWrite) * 100.0))%")
}
}
}
})
}
但是,如果我单击单元格,我的文件就会开始下载。但是我想点击一个单元格(开始显示进度),如果之后我点击不同的单元格,我不想在这个单元格中显示进度,直到第一个文件没有下载。换句话说。我想一次下载一个文件,如果用户点击另一个单元格,这个下载应该在队列中。怎么做?
【问题讨论】:
-
您可以使用 URLSessionConfiguration 设置一次下载的项目数。 sessionConfigue.httpMaximumConnectionsPerHost = 1 所以它会一次启动一个任务。
-
@SaurabhPrajapati 不起作用。