我正在从网上下载一个文件。文件很大,有些时候可能会达到100MB,我想在应用程序转到后台或设备被锁定的时候继续下载。为此,我使用AFNetworking 3.0
[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:myIdentifier];
只要我在WiFi上,它就工作得很好。当我关闭WiFi并打开我的4G蜂窝网络时,它停止响应,并且由于我的下载请求,我没有得到任何数据。如果我使用
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
一切都很好,除了我的下载将不会继续当应用程序转到后台。
我还检查了NSURLSessionConfiguration和NSURLRequest上的allowsCellularAccess和YES的object,但我的下载在蜂窝网络上无法工作。
这是我的完整代码
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:myIdentifier];
configuration.discretionary = YES;
configuration.sessionSendsLaunchEvents = YES;
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:downloadUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSLog(@"Allow Cellular Network : %d",request.allowsCellularAccess);
NSLog(@"Allow Cellular Network for session: %d",configuration.allowsCellularAccess);
NSLog(@"Resource timneout interval: %f",configuration.timeoutIntervalForResource);
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
[self callProgressBlocksForUrl:lesson.archiveUrl withProgress:downloadProgress.fractionCompleted];
});
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSLog(@"Getting Path for File saving");
return [NSURL fileURLWithPath:fullPath];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
NSHTTPURLResponse * myresponse = (NSHTTPURLResponse *)response;
NSLog(@"Video downloaded, headers: %@", [myresponse.allHeaderFields description]);
}];发布于 2016-05-01 15:05:22
您不应该设置discretionary标志。这告诉操作系统等待下载数据,直到一个方便的时间( IIRC,基本上是指设备A.睡眠,B.通电,C.连接到Wi-Fi)。
发布于 2019-08-20 12:51:09
我猜自由裁量标志可能会造成这个问题。正如苹果在文档中所说的那样,当设备有方便的时间和方便的资源时,discretionary标志允许下载。

https://stackoverflow.com/questions/36739217
复制相似问题