苹果官方有个后台下载的DEMO
这个demo 展示了下载一个文件的示例
在新的需求中,要求在一个表单中,能够实现多个任务的后台下载
暂停等需求
于是把苹果的这个工程文件改写
在使用过程中
遇到了 一个很奇怪的问题
就是无论怎么下载
始终只会返回给第一个下载任务的block
找了很久 发现问题出现在
- (NSURLSession *)backgroundSession
{
/*
Using disptach_once here ensures that multiple background sessions with the same identifier are not created in this instance of the application. If you want to support multiple background sessions within a single process, you should create each session with its own identifier.
*/
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.example.apple-samplecode.SimpleBackgroundTransfer.BackgroundSession"];
session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
});
return session;
}
注意到上面的英文
是指 如果要支持多个任务 应该有多个session 来处理
每个session 需要对应一个不同的identifier
这个唯一的identifier 是苹果找到返回上级的唯一标识
所以不管怎么下载 都会返回给最初的请求对象 ,其他请求
对象都不会获取到数据
什么意思呢 就是需要每次创建不同的id
NSURLSession *session = nil;
NSString *identifier = [NSString stringWithFormat:@"%@%@",@"com.example.apple-samplecode.SimpleBackgroundTransfer.BackgroundSession",[self.downloadURLString lastPathComponent]];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:identifier];
session = [NSURLSession sessionWithConfiguration:configuration delegate:(id <NSURLSessionDelegate>)self delegateQueue:nil];
return session;
这样就能够解决问题了
NSURLSessionConfiguration 中
allowsCellularAccess 属性指定是否允许使用蜂窝连接, discretionary属性为YES时表示当程序在后台运作时由系统自己选择最佳的网络连接配置,该属性可以节省通过蜂窝连接的带宽。在使用后台传输数据的时候,建议使用discretionary属性,而不是allowsCellularAccess属性,因为它会把WiFi和电源可用性考虑在内。补充:这个标志允许系统为分配任务进行性能优化。这意味着只有当设备有足够电量时,设备才通过Wifi进行数据传输。如果电量低,或者只仅有一个蜂窝连接,传输任务是不会运行的。后台传输总是在discretionary模式下运行。
本文介绍如何解决iOS应用中使用NSURLSession进行多任务后台下载时遇到的问题,即所有下载任务都返回给首个任务的问题。文章详细解释了背景session的工作原理,并提供了修改后的代码示例。
1823

被折叠的 条评论
为什么被折叠?



