我有包含部分和单元格的集合视图。
我使用此代码下载文件:
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))%")
}
}
}
})
}
但是,如果我单击单元格,则文件开始下载。但是,我想单击一个单元格(开始显示进度),如果此后单击另一个单元格,则在不下载第一个文件之前,我不希望在该单元格中显示进度。换一种说法。我想一次下载一个文件,如果用户单击到另一个单元格,则此下载应该在队列中。怎么做?
答案 0 :(得分:0)
请检查以下代码,它将管理您的所有下载任务
var isDownloading = false{
didSet{
if isDownloading == false{
//remove downloadedTask
if allDownloadTasks.count > 0{
allDownloadTasks.removeFirst()
}
}
}
}
var allDownloadTasks:[URLSessionDownloadTask] = []{
didSet{
if isDownloading == false{
//start next Download
startNextDownload()
}
}
}
func startNextDownload(){
//start download task
if allDownloadTasks.count > 0{
let downloadTask = allDownloadTasks[0]
downloadTask.resume()
}
}
在CollectionViewDidSelect方法中
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
}