Code: Select all
func createDataSource() {
dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { collectionView, indexPath, item in
switch self.sections[indexPath.section].identifier {
case "cell":
let cell = self.configure(DCell.self, with: item, for: indexPath)
if indexPath.row < self.items.count {
let item = self.items[indexPath.row]
switch item.state {
case .downloading: cell.title.text = "\(String(format: "%.f%%", item.progress * 100))"
case .completed: cell.title.text = "Completed"
case .failed: cell.title.text = "Fail"
case .none: break
}
}
return cell
default: return self.configure(DCell.self, with: item, for: indexPath)
}
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// activate the download manager code...
// get progress:
downloadManager.onProgress = { [weak self] (row, collection, progress) in
guard let self = self else { return }
DispatchQueue.main.async {
self.items[row - 1].progress = progress
switch progress {
case 1.0: self.items[row - 1].state = .completed
case _: self.items[row - 1].state = .downloading
}
self.reloadItem(indexPath: .init(row: row - 1, section: 0))
}
}
}
func reloadItem(indexPath: IndexPath) {
guard let needReloadItem = dataSource!.itemIdentifier(for: indexPath) else { return }
var snapshot = NSDiffableDataSourceSnapshot()
snapshot.appendSections(sections)
for section in sections { snapshot.appendItems(section.item, toSection: section) }
dataSource?.apply(snapshot)
snapshot.reloadItems([needReloadItem])
dataSource?.apply(snapshot, animatingDifferences: false)
}
Code: Select all
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if totalBytesExpectedToWrite > 0 {
if let onProgress = onProgress { calculateProgress(session: session, completionHandler: onProgress) }
}
}
private func calculateProgress(session : URLSession, completionHandler : @escaping (Int, Int, Float) -> ()) {
session.getTasksWithCompletionHandler { (tasks, uploads, downloads) in
let progress = downloads.map({ (task) -> Float in
if task.countOfBytesExpectedToReceive > 0 { return Float(task.countOfBytesReceived) / Float(task.countOfBytesExpectedToReceive)
} else { return 0.0 }
})
completionHandler(session.getSessionDescription(), Int(session.accessibilityHint!)!, progress.reduce(0.0, +))
}
}