NSURLSessionDownloadTask在后台自动恢复所有任务 [英] NSURLSessionDownloadTask resumes automatically all task while in background

查看:706
本文介绍了NSURLSessionDownloadTask在后台自动恢复所有任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求按顺序下载文件。目前,我可以在app处于前台时这样做。

I have requirement to download files in serial order. Currently I am able to do that while app is in foreground.

以下是我使用的逻辑。


  1. 全部创建下载任务。

  1. Create all tasks for downloading.

一次恢复一个,当前完成后,从 URLSession:task:didCompleteWithError:

Resume one at a time and as the current finishes resume the next one from URLSession:task:didCompleteWithError:.

当应用程序处于前台时,此逻辑正在运行,但一旦应用程序开始运行背景(通过崩溃)我们再次运行应用程序,然后下载完成所有任务状态已更改为恢复并且所有任务都在同时下载。

This logic is working while app is in foreground but once app started to run in background(By crashing) and we again run the app before download finishes all the tasks state has been changed to resume and all are downloading at the same time.

这是预期的行为或我缺少的任何东西也可以在后台模式下连续订购?

Is this the expected behaviour or anything I am missing to order this in serial in background mode too?

编辑:
我通过创建下载进行检查任务一个接一个。完成第一个任务后,在 setTaskDidCompleteBlock 内创建下一个,依此类推。它只完成第一个任务,然后在 setTaskDidCompleteBlock 内创建任务时该会话崩溃(这只发生在后台模式下运行时,前台工作正常)。

I checked by creating download task one by one. After finishing the first task create next inside setTaskDidCompleteBlock and so on. It only completes the first task and after that session crashed while task created inside setTaskDidCompleteBlock (This happens only when running in background mode, for foreground its working fine).

这是我的崩溃日志屏幕截图:

Here is my crash log screen shots:

任何帮助都将不胜感激。

Any help would be appreciated.

推荐答案

如果你绝对需要按顺序运行这些请求,我建议不要事先实例化所有这些任务,而是一次实例化一个,只实例化下一个一个完成前一个。

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.

这篇关于NSURLSessionDownloadTask在后台自动恢复所有任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆