您可以在后台运行后使用后台任务 API 调用方法(只要您的任务不会花费太长时间 - 通常约 10 分钟是允许的最大时间)。
iOS 不会在应用程序后台运行时触发计时器,因此我发现在应用程序后台运行之前调度后台线程,然后将该线程置于睡眠状态,与计时器具有相同的效果。
将以下代码放入您的应用委托的- (void)applicationWillResignActive:(UIApplication *)application
方法中:
// Dispatch to a background queue
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Tell the system that you want to start a background task
UIBackgroundTaskIdentifier taskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
// Cleanup before system kills the app
}];
// Sleep the block for 5 seconds
[NSThread sleepForTimeInterval:5.0];
// Call the method if the app is backgrounded (and not just inactive)
if (application.applicationState == UIApplicationStateBackground)
[self performSelector:@selector(test)]; // Or, you could just call [self test]; here
// Tell the system that the task has ended.
if (taskID != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:taskID];
}
});