URLSessionDownloadDelegate中didSendBodyData方法未触发问题排查
问题原因及解决方案
你遇到的问题是用错了回调方法:urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:) 是上传数据时的进度回调,用来跟踪向服务器发送数据的进度,并非下载进度的回调接口。
下载任务的进度需要使用 URLSessionDownloadDelegate 协议中的专属方法:urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)。
修正后的代码
将你扩展中的未触发方法替换为以下代码:
extension ViewController: URLSessionDownloadDelegate { // 下载完成回调(保留原正常工作的方法) func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { print("Finished Downloading") } // 下载进度回调(替换原didSendBodyData方法) func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { // 容错处理:避免服务器未返回Content-Length导致的除以0错误 guard totalBytesExpectedToWrite > 0 else { return } let fractionCompleted = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite) print(fractionCompleted) progressView.progress = fractionCompleted } }
额外说明
- 只有当你发起上传请求(比如POST请求发送表单、文件)时,
didSendBodyData方法才会触发,而当前你使用的downloadTask是从服务器拉取数据的操作,不会触发上传相关回调。 - 部分服务器可能不会返回
Content-Length响应头,此时totalBytesExpectedToWrite会返回NSURLSessionTransferSizeUnknown(即-1),必须添加容错判断避免运行时错误。
内容的提问来源于stack exchange,提问作者sumit kumar Pradhan
相关产品推荐
相关产品推荐

