我正在从网上下载一个文件。文件大小有时可能会达到 100MB,我想在应用程序进入后台或设备锁定时继续下载。为此我正在使用AFNetworking 3.0
[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:myIdentifier];
只要我在 WiFi 上,它就可以正常工作。当我关闭 WiFi 并打开我的 4G 蜂窝网络时,它停止响应,并且由于我的下载请求,我没有收到任何数据。如果我使用
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
一切都很好,除了当应用程序进入后台时我的下载不会继续。
我还检查allowsCellularAccess
了NSURLSessionConfiguration
andNSURLRequest
和 object which is 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]);
}];