NSURLSessionDownloadTask resumes automatically all task while in background

荒凉一梦 提交于 2019-12-06 10:40:41

If you absolutely need to run these requests sequentially, I would suggest not instantiating all of these tasks up front, but rather instantiate them one at a time, only instantiating the next one upon the completion of the prior one.

But we must recognize that you pay a significant performance penalty for running the requests sequentially. (And this problem will be magnified when using background sessions.) If at all possible, see if you can change your requests to run concurrently. Clearly, if you need the output of one in order to create the request for another, you're stuck (or at least until your refactor the server code), but that's clearly not the issue here (because you created all of the requests up front). If you're doing this sequential request process for artificial reasons (e.g., the code is populating an array and you want that in order), then you might want to redesign the implementation to remove this artificial constraint.

I have seen this happen too. If you create a downloadTask while the app is in the foreground but do not call resume(), it will not start — however, it will start automatically when the app is backgrounded.

The solution is to explicitly call suspend() on each downloadTask when you create it. Then, when you are ready to start downloading it, call resume().

Apparently a newly created downloadTask is neither suspended nor resumed. Its initial state is not .Running, but when the app is backgrounded it is shifted into .Running because it hasn't been explicitly suspended. This is suprising behavior; I don't know why the background session daemon works this way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!