让NSTimer在后台保持运行

2017-07-26  本文已影响0人  MissLu16

项目中需求所需,遇到这个问题,进行以下解决:

使用NSTimer的时候,发现每次APP进入后台,或者屏幕休眠后,NSTimer就会暂停。为了解决这个问题,翻阅了各种博客和网页。最终在伟大的stackoverflow上找到了一个简单并且真正可行的解决方案!代码如下:

[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];

self.timer = [NSTimerscheduledTimerWithTimeInterval:1 target:selfselector:@selector(timeFireMethod)userInfo:nilrepeats:YES];

[[NSRunLoop currentRunLoop] addTimer:self.timerforMode:NSRunLoopCommonModes];

如果需求是每次app进入后台,NSTimer暂停,重新进入后继续启动,这样的话,可以直接这样

self.timer = [NSTimerscheduledTimerWithTimeInterval:1 target:selfselector:@selector(timeFireMethod)userInfo:nilrepeats:YES];

上一篇 下一篇

猜你喜欢

热点阅读