如果应用程序进入后台(例如,按下主页按钮),我正在尝试正确处理进程中的 NSURLSessionTasks。我目前正在采取将进程内任务复制到后台队列的方法(参见下面的代码)。但是,我发现后台任务的行为不规律并且并不总是完成。可以发现我可能做错了什么/建议最好的方法吗?
- (void)appWillResignActive : (NSNotification *)notification {
UIApplication *app = [UIApplication sharedApplication];
// Register expiring background task
__block UIBackgroundTaskIdentifier bgTaskId =
[app beginBackgroundTaskWithExpirationHandler:^{
bgTaskId = UIBackgroundTaskInvalid;
}];
[self switchToBackground];
[app endBackgroundTask:bgTaskId];
}
- (void)appWillBecomeActive : (NSNotification *)notification {
[self switchToForeground];
}
- (void)switchToBackground
{
NSLog(@"Switch to background line 217 Network Manager");
if ([state isEqualToString: kdownloadManagerStateForeground]) {
[urlSession getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
[downloadTask cancelByProducingResumeData:^(NSData *resumeData) {
NSURLSessionDownloadTask *downloadTask = [self.backgroundSession downloadTaskWithResumeData:resumeData];
[downloadTask resume];
}];
}
}];
state = kdownloadManagerStateBackground;
}
}
- (void)switchToForeground
{
if ([state isEqualToString: kdownloadManagerStateBackground]) {
[backgroundSession getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
[downloadTask cancelByProducingResumeData:^(NSData *resumeData) {
NSURLSessionDownloadTask *downloadTask = [self.urlSession downloadTaskWithResumeData:resumeData];
[downloadTask resume];
}];
}
}];
state = kdownloadManagerStateForeground;
}
}