iphone - 后台的 NSTimers [英] iphone - NSTimers in background

查看:23
本文介绍了iphone - 后台的 NSTimers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im developing an app that has to run in the background. It's a location based app, so it runs all the time, the OS doesn't kill it.

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

It should send some info every 10 secs(just for debugging), I set a timer once its in the background. I set a breakpoint in the function that should be executed every 10 secs, which is never called, but if I pause the app and then continue the timer is called, and then the timer is executed every 10 secs without problems, weird right?

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

I thought that the timer would be executing anyway when I wasn't debugging, but it isn't, same thing as if I didn't pause the debugging.

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

My question is WHY?? The timer is set correctly(I assume) since it works after pausing, but it's not.

有什么想法吗?

我设置定时器的方式是:

The way I set the timer is:

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

在函数中,我连接到一个网络服务.

And in the function I connect to a webservice.

谢谢.

推荐答案

我有一个类似的应用程序设计并且被困在同样的事情上.我在互联网上的某个地方发现的是添加这种类型的声明 applicationDidEnterBackground:

I have a similar app design and was stuck on the same thing. What I found somewhere on the internet is adding this type of statement applicationDidEnterBackground:

    UIBackgroundTaskIdentifier locationUpdater =[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
         [[UIApplication sharedApplication] endBackgroundTask:locationUpdater];
        locationUpdater=UIBackgroundTaskInvalid;
     } ]; 

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

This tells the os that you still have things going and not to stop it.

我的计时器附加到此功能

I have my timer attached to this function

 //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;
}

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

I set the timer in my my location manager delegate methods.

我感觉到你的痛苦.我发现这些东西非常挑剔.这对我有用.我希望它有帮助.我发现您可以在后台执行的操作没有任何真正的限制.

I feel your pain. I found that these things were super finicky. This is what worked for me. I hope it helps. I have found that there isn't any really restrictions in what you can do in the background.

这篇关于iphone - 后台的 NSTimers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆