美文网首页
让NSTimer在后台保持运行

让NSTimer在后台保持运行

作者: MissLu16 | 来源:发表于2017-07-26 15:37 被阅读0次

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

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

    相关文章

      网友评论

          本文标题: 让NSTimer在后台保持运行

          本文链接:https://www.haomeiwen.com/subject/vicokxtx.html