You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 14:32:21