我正在使用 Afnetworking 处理我的项目,我想在后台下载大约 100mb 或 150mb 的大文件,但在苹果文档中他们说后台任务将持续长达 10 分钟,那么我应该如何解决这个问题?
我在互联网上搜索并空闲计时器以禁用它或根据文件设置计时器?(但是我如何根据我的文件大小设置空闲计时器,它也取决于互联网连接)..
在一些 SO post matte 中发布此答案,但我不确定他是否为此afnetworking 背景答案禁用空闲计时器
(void)applicationWillResignActive:(UIApplication *)application {
__block UIBackgroundTaskIdentifier backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^(void) {
[application endBackgroundTask:backgroundTaskIdentifier];
[[YourRestClient sharedClient] cancelAllHTTPOperations];
}];
这是我的afnetworking代码
NSURL *url = [NSURL URLWithString:downloadMainURL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient.operationQueue setMaxConcurrentOperationCount:1];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:downloadPostUrl parameters:postRequest];
AFDownloadRequestOperation *operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:destPath shouldResume:YES];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if(operation.response.statusCode == 200) {
NSLog(@"enable ipad sleep");
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];// enable the idle screen timmer
[loadingHUD hide:TRUE];
// NSLog(@"responseString is %@",[operation responseString]);
}
else{
NSLog(@"setCompletionBlockWithSuccess");
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];// enable the idle screen timmer
[loadingHUD hide:TRUE];
}
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if(operation.response.statusCode!= 200) {
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];// enable the idle screen timmer
[loadingHUD hide:TRUE];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Attention" message:@"download failed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
}
}];
[httpClient enqueueHTTPRequestOperation:operation];
[operation setDownloadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)
{
int filesize = [[NSUserDefaults standardUserDefaults] integerForKey:@"filesize"];
int totalbytes=filesize+bytesWritten;
NSLog(@"productidFileSize value is %f",productidFileSize);
NSLog(@"totalBytesWritten value is %d",totalbytes);
progress = ((float)totalbytes )/ productidFileSize;
NSLog(@"progress value is %f",progress);
loadingHUD.progress = progress;
[[NSUserDefaults standardUserDefaults] setInteger:totalbytes forKey:@"filesize"];
}];
}
}