让NSTimer在后台保持运行

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

使用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];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容