Ios UIBackgroundTaskIdentifier无法工作,请在其过期后重新启动
我有一个应用程序,每5分钟在后台使用UIBackgroundTaskIdentifier通过RESTAPI从服务器获取一些内容。我的问题是,它可以正常工作1,2个小时,然后在过期后,它永远不会重新启动后台任务。我使用的代码如下所示 在AppDelegate.m中Ios UIBackgroundTaskIdentifier无法工作,请在其过期后重新启动,ios,iphone,ios7,uibackgroundtask,Ios,Iphone,Ios7,Uibackgroundtask,我有一个应用程序,每5分钟在后台使用UIBackgroundTaskIdentifier通过RESTAPI从服务器获取一些内容。我的问题是,它可以正常工作1,2个小时,然后在过期后,它永远不会重新启动后台任务。我使用的代码如下所示 在AppDelegate.m中 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UIApplication* app = [UIApplication sharedApplication];
self.expirationHandler = ^{
[app endBackgroundTask:self.bgTask];
self.bgTask = UIBackgroundTaskInvalid;
// self.bgTask = [app beginBackgroundTaskWithExpirationHandler:expirationHandler];
NSLog(@"Expired");
self.jobExpired = YES;
while(self.jobExpired) {
// spin while we wait for the task to actually end.
[NSThread sleepForTimeInterval:1];
}
self.bgTask = [app beginBackgroundTaskWithExpirationHandler:expirationHandler];
// Restart the background task so we can run forever.
[self startBackgroundTask];
};
self.bgTask = [app beginBackgroundTaskWithExpirationHandler:expirationHandler];
[self monitorBatteryStateInBackground];
}
- (void)monitorBatteryStateInBackground
{
NSLog(@"Monitoring update");
self.background = YES;
[self startBackgroundTask];
}
- (void)startBackgroundTask
{
NSLog(@"Restarting task");
// Start the long-running task.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// When the job expires it still keeps running since we never exited it. Thus have the expiration handler
// set a flag that the job expired and use that to exit the while loop and end the task.
while(self.background && !self.jobExpired)
{
[self uploadPhotostoServer];
[NSThread sleepForTimeInterval:240.0];
}
self.jobExpired = NO;
});
}
在expired部分中,它确实出现了,但从未调用方法[self startBackgroundTask]
任何帮助都将不胜感激。您不能永远在IOS的后台运行。最终,您将消耗大约3分钟的可用累积背景时间。您可以使用后台获取,但不会每5分钟运行一次。最好将应用程序设计为在实际有新应用程序时使用推送通知data@Paulw11,你说累计3分钟,这意味着我只允许在应用程序进入后台后调用后台提取总共3分钟,或者这一次是一次后台提取请求?我相信这3分钟会在应用程序进入前台后重置-你可以检查UIApplication上的BackgroundTimeRequireming属性,查看时间在任何时候都会留下