iphone - NSTimers在背景中

sub*_*arb 11 debugging objective-c nstimer

我正在开发一个必须在后台运行的应用程序.它是一个基于位置的应用程序,所以它一直运行,操作系统不会杀死它.

它应该每10秒发送一些信息(仅用于调试),我在后台设置一个计时器.我在函数中设置一个断点,应该每10秒执行一次,这是永远不会被调用的,但如果我暂停应用程序然后继续调用计时器,然后计时器每10秒执行一次没有问题,怪异对吗?

我以为计时器会在我没有调试的时候执行,但事实并非如此,就好像我没有暂停调试一样.

我的问题是为什么?计时器设置正确(我假设),因为它在暂停后工作,但事实并非如此.

有任何想法吗?

我设置计时器的方式是:

self.timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(doStuff) userInfo:nil repeats:YES];
Run Code Online (Sandbox Code Playgroud)

在函数中我连接到webservice.

谢谢.

uta*_*hak 20

我有一个类似的应用程序设计,并坚持同样的事情.我在互联网上找到的是添加这种类型的声明applicationDidEnterBackground:

    UIBackgroundTaskIdentifier locationUpdater =[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
         [[UIApplication sharedApplication] endBackgroundTask:locationUpdater];
        locationUpdater=UIBackgroundTaskInvalid;
     } ]; 
Run Code Online (Sandbox Code Playgroud)

这告诉操作系统你还有事情要做,而不是阻止它.

我把我的计时器连接到这个功能

 //this is a wrapper method to fit the required selector signature
- (void)timeIntervalEnded:(NSTimer*)timer {
     [self writeToLog:[NSString stringWithFormat:@"Timer Ended On %@",[NSDate date]]];
     [self startReadingLocation];
     [timer invalidate];
     timer=nil;
}
Run Code Online (Sandbox Code Playgroud)

我在我的位置管理器委托方法中设置了计时器.

我感觉到你的痛苦.我发现这些东西都很挑剔.这对我有用.我希望它有所帮助.我发现你在后台可以做的事情没有任何限制.

  • 这是正确的,我在app委托类之外有一个持续运行/到期/重置的计时器.并且只是在它进入后台之前就开始了BackBackgroundTaskWithExpirationHandler.我的计时器方法正如我发布的那样.确保您在plist的背景模式字段中有位置 (2认同)
  • 除了在UIBackgroundTaskIdentifier之前需要__block之外,这对我来说非常合适.谢谢! (2认同)