如果您正在执行一些重要或珍贵的下载或上传操作并且您的应用程序进入后台,在这种情况下,您可以向“IOS”请求额外的时间来完成您的工作,当您的应用程序处于后台时,它会额外授予 10 分钟的时间来完成该操作模式。
但请记住,您的操作必须重要且可接受,否则您的应用可能会被 Apple 审核流程拒绝。
有关更多详细信息,请参阅 Apple 文档以了解后台执行和多任务处理
现在,结束我的一些操作的时间点,在后台继续您的任务,您可以使用以下方法执行,无需管理 Application Delegate 方法。只需使用以下代码段,不要使用委托进行下载或上传。
if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4
if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking
UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance
__block UIBackgroundTaskIdentifier background_task; //Create a task object
background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
[application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
background_task = UIBackgroundTaskInvalid; //Set the task to be invalid
//System will be shutting down the app at any point in time now
}];
//Background tasks require you to use asyncrous tasks
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Perform your tasks that your application requires
NSLog(@"\n\nRunning in the background!\n\n");
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"YOUR HOST URL"]];
NSURLResponse *response = nil;
NSError *requestError = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"ResponseString:%@",responseString);
[application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform
background_task = UIBackgroundTaskInvalid; //Invalidate the background_task
});
}
}