NSURLSessionDownloadTask 在挂起时继续下载

NSURLSessionDownloadTask continues download while suspended

我正在使用 NSURLSessionDownloadTask 下载文件。在应用程序的某一时刻,有必要暂停下载一小段时间,然后再继续下载。我尝试使用暂停方法暂停下载,但任务继续下载。 NSURLSessionTask 方法暂停状态的 Apple 文档:

A task, while suspended, produces no network traffic and is not subject to timeouts. A download task can continue transferring data at a later time. All other tasks must start over when resumed.

这似乎表明我做的是对的,但结果却不如预期。我能够在 Playground 中使用以下代码重现它。

import UIKit

let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "some-identifier")
let backgroundSession = Foundation.URLSession(configuration: backgroundSessionConfiguration, delegate: nil, delegateQueue: nil)

let request = URLRequest(url: URL(string: "http://google.com")!)
let task = backgroundSession.downloadTask(with: request)

task.state.rawValue

task.resume()
task.state.rawValue

task.suspend()
task.state.rawValue

sleep(10)

task.state.rawValue

任务状态的预期结果为 1、0、1、1(0 - 正在下载,1 - 已暂停,2 - 已取消,3 - 已完成)。实际结果是 1, 0, 1, 3。这意味着虽然任务被挂起,但它仍然会继续下载并在下载完成后将自己标记为完成。

app中的设置比较复杂,任务状态不能一直复制(在Playground中结果似乎总是一样)但是暂停任务后的结果总是文件下载成功(包括那个调用进度回调)。

问题: 难道我做错了什么?我是否误解了 Apple 文档,无法以这种方式暂停下载任务?

当我在应用程序中遇到这个问题时,我的第一个直觉是我在其他地方调用 resume 导致下载继续,但在调试代码 + Playground 调查结果支持后,情况似乎并非如此这也是。

可能不是您要找的答案,但 Apple Dev Relations 代表 confirmed in their dev forums 后台下载在某些情况下不会 真的 通过使用暂停suspend:

[...] a suspended task can still be active on the wire; all that the suspend does is prevent it making progress internally, issuing callbacks, and so on.

他们继续建议改用 cancel(byProducingResumeData:)

if you're implementing a long-term pause (for example, the user wants to pause a download), you'd be better off calling -cancelByProducingResumeData:.