我有包含部分和单元格的 Collection View 。
我使用这段代码来下载文件:
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))%")
}
}
}
})
}
但如果我点击单元格,我的文件就会开始下载。但是我想点击一个单元格(开始显示进度),如果之后我点击不同的单元格,我不想在这个单元格中显示进度,直到第一个文件未下载。换句话说。我想一次下载一个文件,如果用户点击另一个单元格,这个下载应该在队列中。怎么做?
最佳答案
请检查下面的代码,它将管理您所有的下载任务
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
}
关于ios - swift:可以同时下载的文件数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51741593/