我正在从网上下载文件。文件大小有时可能有时会达到100MB,我想继续下载到应用程序转到后台或设备被锁定时。为此我使用AFNetworking 3.0
[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:myIdentifier];
只要我在WiFi上,它就能正常工作。当我关闭WiFi并打开我的4G蜂窝网络时,它停止响应,我的下载请求没有数据。如果我使用
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
除了我的下载在应用程序进入后台时无法继续下去,所以一切都很好。
我还检查了allowsCellularAccess
和NSURLSessionConfiguration
上的NSURLRequest
以及YES
的对象,但我的下载在蜂窝网络上无效。
这是我的完整代码
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]);
}];