点击单元格下载文件并向上或向下滚动时应用程序崩溃 table

App crash when tap a cell to download a file and scroll up or down the table

当我点击一个单元格下载音频文件时,我有一个应用程序工作正常,但如果我点击一个单元格然后尝试向上或向下滚动,然后再完成下载,它就会崩溃!

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    
    let percentege = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
    
    DispatchQueue.main.async {
        let cell = self.audioTableView.cellForRow(at: self.selectedCellIndex) as! AudioTableViewCell
        
        cell.progressV.progress = percentege
        
    }
    
}

首先你应该避免强制展开,尝试使用 guard 语句。

关于崩溃,看看您是否正在更新 selectedCellIndex 并在任何地方调用相同的下载任务。我怀疑 selectedCellIndex 设置为某个不符合预期的值。

从你的附加图片来看,selectedCellIndex 是一个可选变量。 所以,在使用它之前你需要检查它是否为 nil,然后你应该删除强制展开以避免像这样的崩溃

DispatchQueue.main.async {
    if self.selectedCellIndex != nil{
        if let cell = self.audioTableView.cellForRow(at: self.selectedCellIndex) as? AudioTableViewCell{
            cell.progressV.progress = percentege
        }

    }   
}